Step 1: Install Required Libraries
First, make sure you have the necessary libraries installed. Open your terminal or command prompt and run the following commands to install pyqrcode and tkinter:
Step 2: Open up your text editor (I like Nano) and begin coding
$ sudo pip install pyqrcode
$ sudo pip install tkinter
$ sudo pip install pypng
Start by importing the required libraries in your Python script:
import tkinter as tk
from tkinter import filedialog
Step 3: Define the QR Code Generation Function
Next, define the generate_qr() function. This function will be called when the "Generate" button is clicked. Inside this function, we'll generate the QR code based on the user input and save it as a PNG file:
def generate_qr():
qr = pyqrcode.create(entry.get())
filename = filedialog.asksaveasfilename(defaultextension='.png')
qr.png(filename, scale=8)
window.destroy()
In this function, we first create a QR code using pyqrcode.create(). The data for the QR code is obtained from the entry widget using entry.get(). Next, we open a file dialog using filedialog.asksaveasfilename() to let the user choose the location and name of the PNG file to save the QR code. Finally, we save the QR code as a PNG file using qr.png() with a specified scale of 8, and then close the GUI window using window.destroy().
Create the main GUI window using the tkinter library:
window = tk.Tk()
window.title('QR Code Generator')
Add the necessary GUI widgets to the window, including a label, an entry field, and a button:
label = tk.Label(window, text='Enter data:')
label.pack()
entry = tk.Entry(window)
entry.pack()
button = tk.Button(window, text='Generate', command=generate_qr)
button.pack()
Run the main GUI loop using window.mainloop():
window.mainloop()
Save your script with a .py extension (e.g., qr_code_generator.py) and run it using Python. The GUI window will appear, allowing you to enter the data for the QR code. After entering the data, click the "Generate" button. A file dialog will open where you can choose the location and name of the PNG file to save the QR code. Once you select the location and provide a file name, the QR code will be generated and saved as a PNG file. The GUI window will then close. (Note: Code must be run as sudo or root)
import pyqrcode
import tkinter as tk
from tkinter import filedialog
def generate_qr():
qr = pyqrcode.create(entry.get())
filename = filedialog.asksaveasfilename(defaultextension='.png')
qr.png(filename, scale=8)
window.destroy()
window = tk.Tk()
window.title('QR Code Generator')
label = tk.Label(window, text='Enter data:')
label.pack()
entry = tk.Entry(window)
entry.pack()
button = tk.Button(window, text='Generate', command=generate_qr)
button.pack()
window.mainloop()