How to Print Hard Copy using Tkinter?

PythonTkinterGUI-Programming

Tkinter allows developers to interact with the files inside the local system. In this article, we will see how to print a hardcopy of a file using Tkinter packages such as filedialog and win32api module.

In order to import these packages, we have to first install these modules in our environment. To install win32api, we will use pip install pywin32

Example

#import the required libraries
from tkinter import *
from tkinter import filedialog
import win32api

#Create an instance of tkinter frame or window
win= Tk()

win.title('Print Hard Copy')
win.geometry("700x400")

#Define function
def print_file():
   file= filedialog.askopenfilename(initialdir="/", title="Select any file",filetypes=(("Text files", "*.txt"), ("all files", "*.*")))
   if file:
      #Print Hard copy using Printer
      win32api.ShellExecute(0, "Choose a File", file, None, ".", 0)
#Create a button for printing event
button= Button(win, text="Choose a File to Print", command=print_file).pack(pady= 20)

#Keep running the window or frame
win.mainloop()

Output

Running the above code will produce the following output −

If you click the button, it will open up a folder from where you can select a file to print.

raja
Published on 06-Mar-2021 08:13:41
Advertisements