Hướng dẫn hôm nay sẽ tập trung vào hai tiện ích Tkinter thường được sử dụng --
Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
8 và Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
9. Các nút có thể được nhìn thấy ở mọi nơi trong các ứng dụng GUI. Chúng rất hữu ích để cho phép người dùng tương tác với một ứng dụng, tạo các tùy chọn và lựa chọn để người dùng chọn. Trong hướng dẫn trước, chúng ta đã xem qua cách sử dụng tiện ích Nút TkinterTạo Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
8 Widget
Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
Nút kiểm là một tiện ích được sử dụng rất phổ biến. Chúng rất tuyệt vời bất cứ khi nào người dùng cần chọn nhiều mục trong cửa sổ GUI hoặc khi bạn cần kiểm soát một tính năng của ứng dụng, bật và tắt tính năng đó bằng nút kiểm. Chức năng này hữu ích khi bạn muốn bật/tắt các tính năng như hiển thị hoặc ẩn thanh công cụ
Các tiện ích
Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
8 cũng có thể được sử dụng để gọi các phương thức Python hoặc các hàm tùy chỉnh bằng cách sử dụng đối số var = IntVar[] # variable class
item1 = Checkbutton[root, text="tuna fish",
variable=var, command=selectItems]
item1.pack[anchor='w']
def selectItems[]:
print[var.get[]] # prints 1 or 0
if var.get[]: # If the button is checked,
print[item1['text']] # Print print the cb's text
2. Mỗi nút kiểm cần phải có một biến tương ứng được liên kết với nó. Các biến kiểm soát được tạo bằng cách sử dụng các lớp biến -- var = IntVar[] # variable class
item1 = Checkbutton[root, text="tuna fish",
variable=var, command=selectItems]
item1.pack[anchor='w']
def selectItems[]:
print[var.get[]] # prints 1 or 0
if var.get[]: # If the button is checked,
print[item1['text']] # Print print the cb's text
3, var = IntVar[] # variable class
item1 = Checkbutton[root, text="tuna fish",
variable=var, command=selectItems]
item1.pack[anchor='w']
def selectItems[]:
print[var.get[]] # prints 1 or 0
if var.get[]: # If the button is checked,
print[item1['text']] # Print print the cb's text
4, Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
0, và Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
1 -- có thể được sử dụng để theo dõi các thay đổi đối với tiện ích TkinterChúng ta hãy xem một đoạn mã nhỏ thiết lập một
Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
8trăn
var = IntVar[] # variable class
item1 = Checkbutton[root, text="tuna fish",
variable=var, command=selectItems]
item1.pack[anchor='w']
def selectItems[]:
print[var.get[]] # prints 1 or 0
if var.get[]: # If the button is checked,
print[item1['text']] # Print print the cb's text
Đầu tiên, chúng ta tạo biến số nguyên,
Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
3, được sử dụng để theo dõi trạng thái của nút kiểm. Tiếp theo, chúng tôi tạo một phiên bản của Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
8. Đối với các tham số, chúng tôi đặt Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
5 tiện ích mẹ, Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
6, Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
7 liên kết với tiện ích và chức năng mà tiện ích sẽ gọi khi người dùng tương tác với tiện ích đó. Cuối cùng, chúng tôi sử dụng Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
8 để sắp xếp tiện ích con trong cửa sổTrong phương thức
Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
9 , chúng tôi sử dụng from tkinter import [Tk, ttk, Label, Frame, Button,
Checkbutton, Radiobutton, IntVar, HORIZONTAL]
class SimpleGUI[Tk]:
def __init__[self]:
super[].__init__[]
self.initializeUI[]
def initializeUI[self]:
self.title["Food Order Form"]
self.minsize[300, 200] # width, height
self.geometry["400x350+50+50"]
self.setupWindow[]
def setupWindow[self]:
""" Set up the widgets."""
title = Label[self, text="Food Order Form",
font=['Helvetica', 20], bd=10]
title.pack[]
line = ttk.Separator[self, orient=HORIZONTAL]
line.pack[fill='x']
order_label = Label[self, text="What would you like to order?", bd=10]
order_label.pack[anchor='w']
foods_list = ["Sandwich", "Salad", "Soup", "Pizza"]
self.foods_dict = {}
# Populate the dictionary with checkbutton widgets
for i, food_item in enumerate[foods_list]:
# Set the text for each checkbutton
self.foods_dict[food_item] = Checkbutton[self, text=food_item]
# Create a new instance of IntVar[] for each checkbutton
self.foods_dict[food_item].var = IntVar[]
# Set the variable parameter of the checkbutton
self.foods_dict[food_item]['variable'] = self.foods_dict[food_item].var
# Arrange the checkbutton in the window
self.foods_dict[food_item].pack[anchor='w']
payment_label = Label[self, text="How do you want to pay?", bd=10]
payment_label.pack[anchor='w']
# Create integer variable
self.var = IntVar[]
self.var.set[0] # Use set[] initialize the variable
self.payment_methods = ["PayPal", "Credit Card", "Other"]
for i, method in enumerate[self.payment_methods]:
self.pymt_method = Radiobutton[self, text=method, variable=self.var, value=i]
self.pymt_method.pack[anchor='w']
# Use ttk to add styling to button
style = ttk.Style[]
style.configure['TButton', bg='skyblue', fg='white']
# Create button that will call the method to display text and
# close the program
next_button = ttk.Button[self, text="Next", command=self.printResults]
next_button.pack[]
def printResults[self]:
"""Print the results of the checkboxes and radio buttons."""
for cb in self.foods_dict.values[]:
if cb.var.get[]:
print['Item selected: {}'.format[cb['text']]]
index = self.var.get[]
print["Payment method: {}".format[self.payment_methods[index]]]
self.quit[]
if __name__ == "__main__":
app = SimpleGUI[]
app.mainloop[]
0 để đọc giá trị hiện tại của biến. Nếu bạn muốn chỉ định giá trị của một biến, hãy sử dụng phương thức from tkinter import [Tk, ttk, Label, Frame, Button,
Checkbutton, Radiobutton, IntVar, HORIZONTAL]
class SimpleGUI[Tk]:
def __init__[self]:
super[].__init__[]
self.initializeUI[]
def initializeUI[self]:
self.title["Food Order Form"]
self.minsize[300, 200] # width, height
self.geometry["400x350+50+50"]
self.setupWindow[]
def setupWindow[self]:
""" Set up the widgets."""
title = Label[self, text="Food Order Form",
font=['Helvetica', 20], bd=10]
title.pack[]
line = ttk.Separator[self, orient=HORIZONTAL]
line.pack[fill='x']
order_label = Label[self, text="What would you like to order?", bd=10]
order_label.pack[anchor='w']
foods_list = ["Sandwich", "Salad", "Soup", "Pizza"]
self.foods_dict = {}
# Populate the dictionary with checkbutton widgets
for i, food_item in enumerate[foods_list]:
# Set the text for each checkbutton
self.foods_dict[food_item] = Checkbutton[self, text=food_item]
# Create a new instance of IntVar[] for each checkbutton
self.foods_dict[food_item].var = IntVar[]
# Set the variable parameter of the checkbutton
self.foods_dict[food_item]['variable'] = self.foods_dict[food_item].var
# Arrange the checkbutton in the window
self.foods_dict[food_item].pack[anchor='w']
payment_label = Label[self, text="How do you want to pay?", bd=10]
payment_label.pack[anchor='w']
# Create integer variable
self.var = IntVar[]
self.var.set[0] # Use set[] initialize the variable
self.payment_methods = ["PayPal", "Credit Card", "Other"]
for i, method in enumerate[self.payment_methods]:
self.pymt_method = Radiobutton[self, text=method, variable=self.var, value=i]
self.pymt_method.pack[anchor='w']
# Use ttk to add styling to button
style = ttk.Style[]
style.configure['TButton', bg='skyblue', fg='white']
# Create button that will call the method to display text and
# close the program
next_button = ttk.Button[self, text="Next", command=self.printResults]
next_button.pack[]
def printResults[self]:
"""Print the results of the checkboxes and radio buttons."""
for cb in self.foods_dict.values[]:
if cb.var.get[]:
print['Item selected: {}'.format[cb['text']]]
index = self.var.get[]
print["Payment method: {}".format[self.payment_methods[index]]]
self.quit[]
if __name__ == "__main__":
app = SimpleGUI[]
app.mainloop[]
1 Tạo Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
9 Widget
Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
Trong khi tiện ích
Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
8 hữu ích để chọn một số lựa chọn, thì Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
9 thường được sử dụng để chọn một lựa chọn trong số nhiều lựa chọn. Radiobuttons cũng có thể được sử dụng để gọi các hàm Python khi được nhấp vàoĐể đạt được tính độc quyền giữa các nút radio trong một nhóm, chúng phải chia sẻ cùng một biến. Điều này có nghĩa là khi một radiobutton trong một nhóm được chọn, bất kỳ tiện ích được chọn nào khác sẽ bị bỏ chọn. Bạn có thể thấy điều này được thể hiện trong đoạn mã bên dưới
trăn
Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
Bạn có thể thấy giao diện của các tiện ích radiobutton trong hình ảnh sau
Quá trình tạo nút bấm tương tự như nút kiểm tra. Một tham số bổ sung mà chúng ta cần chuyển là
from tkinter import [Tk, ttk, Label, Frame, Button,
Checkbutton, Radiobutton, IntVar, HORIZONTAL]
class SimpleGUI[Tk]:
def __init__[self]:
super[].__init__[]
self.initializeUI[]
def initializeUI[self]:
self.title["Food Order Form"]
self.minsize[300, 200] # width, height
self.geometry["400x350+50+50"]
self.setupWindow[]
def setupWindow[self]:
""" Set up the widgets."""
title = Label[self, text="Food Order Form",
font=['Helvetica', 20], bd=10]
title.pack[]
line = ttk.Separator[self, orient=HORIZONTAL]
line.pack[fill='x']
order_label = Label[self, text="What would you like to order?", bd=10]
order_label.pack[anchor='w']
foods_list = ["Sandwich", "Salad", "Soup", "Pizza"]
self.foods_dict = {}
# Populate the dictionary with checkbutton widgets
for i, food_item in enumerate[foods_list]:
# Set the text for each checkbutton
self.foods_dict[food_item] = Checkbutton[self, text=food_item]
# Create a new instance of IntVar[] for each checkbutton
self.foods_dict[food_item].var = IntVar[]
# Set the variable parameter of the checkbutton
self.foods_dict[food_item]['variable'] = self.foods_dict[food_item].var
# Arrange the checkbutton in the window
self.foods_dict[food_item].pack[anchor='w']
payment_label = Label[self, text="How do you want to pay?", bd=10]
payment_label.pack[anchor='w']
# Create integer variable
self.var = IntVar[]
self.var.set[0] # Use set[] initialize the variable
self.payment_methods = ["PayPal", "Credit Card", "Other"]
for i, method in enumerate[self.payment_methods]:
self.pymt_method = Radiobutton[self, text=method, variable=self.var, value=i]
self.pymt_method.pack[anchor='w']
# Use ttk to add styling to button
style = ttk.Style[]
style.configure['TButton', bg='skyblue', fg='white']
# Create button that will call the method to display text and
# close the program
next_button = ttk.Button[self, text="Next", command=self.printResults]
next_button.pack[]
def printResults[self]:
"""Print the results of the checkboxes and radio buttons."""
for cb in self.foods_dict.values[]:
if cb.var.get[]:
print['Item selected: {}'.format[cb['text']]]
index = self.var.get[]
print["Payment method: {}".format[self.payment_methods[index]]]
self.quit[]
if __name__ == "__main__":
app = SimpleGUI[]
app.mainloop[]
5 được liên kết với từng nút radio riêng lẻ. Nếu bạn có nhiều tiện ích nút radio cần tạo, hãy thử sử dụng vòng lặp from tkinter import [Tk, ttk, Label, Frame, Button,
Checkbutton, Radiobutton, IntVar, HORIZONTAL]
class SimpleGUI[Tk]:
def __init__[self]:
super[].__init__[]
self.initializeUI[]
def initializeUI[self]:
self.title["Food Order Form"]
self.minsize[300, 200] # width, height
self.geometry["400x350+50+50"]
self.setupWindow[]
def setupWindow[self]:
""" Set up the widgets."""
title = Label[self, text="Food Order Form",
font=['Helvetica', 20], bd=10]
title.pack[]
line = ttk.Separator[self, orient=HORIZONTAL]
line.pack[fill='x']
order_label = Label[self, text="What would you like to order?", bd=10]
order_label.pack[anchor='w']
foods_list = ["Sandwich", "Salad", "Soup", "Pizza"]
self.foods_dict = {}
# Populate the dictionary with checkbutton widgets
for i, food_item in enumerate[foods_list]:
# Set the text for each checkbutton
self.foods_dict[food_item] = Checkbutton[self, text=food_item]
# Create a new instance of IntVar[] for each checkbutton
self.foods_dict[food_item].var = IntVar[]
# Set the variable parameter of the checkbutton
self.foods_dict[food_item]['variable'] = self.foods_dict[food_item].var
# Arrange the checkbutton in the window
self.foods_dict[food_item].pack[anchor='w']
payment_label = Label[self, text="How do you want to pay?", bd=10]
payment_label.pack[anchor='w']
# Create integer variable
self.var = IntVar[]
self.var.set[0] # Use set[] initialize the variable
self.payment_methods = ["PayPal", "Credit Card", "Other"]
for i, method in enumerate[self.payment_methods]:
self.pymt_method = Radiobutton[self, text=method, variable=self.var, value=i]
self.pymt_method.pack[anchor='w']
# Use ttk to add styling to button
style = ttk.Style[]
style.configure['TButton', bg='skyblue', fg='white']
# Create button that will call the method to display text and
# close the program
next_button = ttk.Button[self, text="Next", command=self.printResults]
next_button.pack[]
def printResults[self]:
"""Print the results of the checkboxes and radio buttons."""
for cb in self.foods_dict.values[]:
if cb.var.get[]:
print['Item selected: {}'.format[cb['text']]]
index = self.var.get[]
print["Payment method: {}".format[self.payment_methods[index]]]
self.quit[]
if __name__ == "__main__":
app = SimpleGUI[]
app.mainloop[]
6 để khởi tạo chúngThông tin thêm Nhận sách
Một ví dụ GUI đơn giản
Bây giờ, hãy xem một ví dụ kết hợp các tiện ích
Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
8 và Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
9 thành một GUI đặt hàng thực phẩm rất đơn giảnChúng tôi sử dụng Lập trình hướng đối tượng [OOP] trong chương trình sau. Nếu bạn không quen thuộc với OOP, vui lòng xem tài liệu Python về cách sử dụng các lớp hoặc các hướng dẫn trực tuyến khác để giúp bạn bắt đầu
trăn
from tkinter import [Tk, ttk, Label, Frame, Button,
Checkbutton, Radiobutton, IntVar, HORIZONTAL]
class SimpleGUI[Tk]:
def __init__[self]:
super[].__init__[]
self.initializeUI[]
def initializeUI[self]:
self.title["Food Order Form"]
self.minsize[300, 200] # width, height
self.geometry["400x350+50+50"]
self.setupWindow[]
def setupWindow[self]:
""" Set up the widgets."""
title = Label[self, text="Food Order Form",
font=['Helvetica', 20], bd=10]
title.pack[]
line = ttk.Separator[self, orient=HORIZONTAL]
line.pack[fill='x']
order_label = Label[self, text="What would you like to order?", bd=10]
order_label.pack[anchor='w']
foods_list = ["Sandwich", "Salad", "Soup", "Pizza"]
self.foods_dict = {}
# Populate the dictionary with checkbutton widgets
for i, food_item in enumerate[foods_list]:
# Set the text for each checkbutton
self.foods_dict[food_item] = Checkbutton[self, text=food_item]
# Create a new instance of IntVar[] for each checkbutton
self.foods_dict[food_item].var = IntVar[]
# Set the variable parameter of the checkbutton
self.foods_dict[food_item]['variable'] = self.foods_dict[food_item].var
# Arrange the checkbutton in the window
self.foods_dict[food_item].pack[anchor='w']
payment_label = Label[self, text="How do you want to pay?", bd=10]
payment_label.pack[anchor='w']
# Create integer variable
self.var = IntVar[]
self.var.set[0] # Use set[] initialize the variable
self.payment_methods = ["PayPal", "Credit Card", "Other"]
for i, method in enumerate[self.payment_methods]:
self.pymt_method = Radiobutton[self, text=method, variable=self.var, value=i]
self.pymt_method.pack[anchor='w']
# Use ttk to add styling to button
style = ttk.Style[]
style.configure['TButton', bg='skyblue', fg='white']
# Create button that will call the method to display text and
# close the program
next_button = ttk.Button[self, text="Next", command=self.printResults]
next_button.pack[]
def printResults[self]:
"""Print the results of the checkboxes and radio buttons."""
for cb in self.foods_dict.values[]:
if cb.var.get[]:
print['Item selected: {}'.format[cb['text']]]
index = self.var.get[]
print["Payment method: {}".format[self.payment_methods[index]]]
self.quit[]
if __name__ == "__main__":
app = SimpleGUI[]
app.mainloop[]
GUI hoàn chỉnh có thể được nhìn thấy trong hình ảnh ở phần đầu của hướng dẫn này
Giải trình
Bắt đầu bằng cách nhập các mô-đun mà chúng tôi cần từ
from tkinter import [Tk, ttk, Label, Frame, Button,
Checkbutton, Radiobutton, IntVar, HORIZONTAL]
class SimpleGUI[Tk]:
def __init__[self]:
super[].__init__[]
self.initializeUI[]
def initializeUI[self]:
self.title["Food Order Form"]
self.minsize[300, 200] # width, height
self.geometry["400x350+50+50"]
self.setupWindow[]
def setupWindow[self]:
""" Set up the widgets."""
title = Label[self, text="Food Order Form",
font=['Helvetica', 20], bd=10]
title.pack[]
line = ttk.Separator[self, orient=HORIZONTAL]
line.pack[fill='x']
order_label = Label[self, text="What would you like to order?", bd=10]
order_label.pack[anchor='w']
foods_list = ["Sandwich", "Salad", "Soup", "Pizza"]
self.foods_dict = {}
# Populate the dictionary with checkbutton widgets
for i, food_item in enumerate[foods_list]:
# Set the text for each checkbutton
self.foods_dict[food_item] = Checkbutton[self, text=food_item]
# Create a new instance of IntVar[] for each checkbutton
self.foods_dict[food_item].var = IntVar[]
# Set the variable parameter of the checkbutton
self.foods_dict[food_item]['variable'] = self.foods_dict[food_item].var
# Arrange the checkbutton in the window
self.foods_dict[food_item].pack[anchor='w']
payment_label = Label[self, text="How do you want to pay?", bd=10]
payment_label.pack[anchor='w']
# Create integer variable
self.var = IntVar[]
self.var.set[0] # Use set[] initialize the variable
self.payment_methods = ["PayPal", "Credit Card", "Other"]
for i, method in enumerate[self.payment_methods]:
self.pymt_method = Radiobutton[self, text=method, variable=self.var, value=i]
self.pymt_method.pack[anchor='w']
# Use ttk to add styling to button
style = ttk.Style[]
style.configure['TButton', bg='skyblue', fg='white']
# Create button that will call the method to display text and
# close the program
next_button = ttk.Button[self, text="Next", command=self.printResults]
next_button.pack[]
def printResults[self]:
"""Print the results of the checkboxes and radio buttons."""
for cb in self.foods_dict.values[]:
if cb.var.get[]:
print['Item selected: {}'.format[cb['text']]]
index = self.var.get[]
print["Payment method: {}".format[self.payment_methods[index]]]
self.quit[]
if __name__ == "__main__":
app = SimpleGUI[]
app.mainloop[]
9. Chúng ta cần tạo một lớp cho cửa sổ của mình, Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
80, kế thừa từ Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
81. Tiếp theo, khởi tạo các tham số của giao diệnTrong phương thức
Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
82, chúng tôi thiết lập các tiện ích con Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
83, Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
8 và Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
9 và các biến tương ứng của chúng. Vòng lặp from tkinter import [Tk, ttk, Label, Frame, Button,
Checkbutton, Radiobutton, IntVar, HORIZONTAL]
class SimpleGUI[Tk]:
def __init__[self]:
super[].__init__[]
self.initializeUI[]
def initializeUI[self]:
self.title["Food Order Form"]
self.minsize[300, 200] # width, height
self.geometry["400x350+50+50"]
self.setupWindow[]
def setupWindow[self]:
""" Set up the widgets."""
title = Label[self, text="Food Order Form",
font=['Helvetica', 20], bd=10]
title.pack[]
line = ttk.Separator[self, orient=HORIZONTAL]
line.pack[fill='x']
order_label = Label[self, text="What would you like to order?", bd=10]
order_label.pack[anchor='w']
foods_list = ["Sandwich", "Salad", "Soup", "Pizza"]
self.foods_dict = {}
# Populate the dictionary with checkbutton widgets
for i, food_item in enumerate[foods_list]:
# Set the text for each checkbutton
self.foods_dict[food_item] = Checkbutton[self, text=food_item]
# Create a new instance of IntVar[] for each checkbutton
self.foods_dict[food_item].var = IntVar[]
# Set the variable parameter of the checkbutton
self.foods_dict[food_item]['variable'] = self.foods_dict[food_item].var
# Arrange the checkbutton in the window
self.foods_dict[food_item].pack[anchor='w']
payment_label = Label[self, text="How do you want to pay?", bd=10]
payment_label.pack[anchor='w']
# Create integer variable
self.var = IntVar[]
self.var.set[0] # Use set[] initialize the variable
self.payment_methods = ["PayPal", "Credit Card", "Other"]
for i, method in enumerate[self.payment_methods]:
self.pymt_method = Radiobutton[self, text=method, variable=self.var, value=i]
self.pymt_method.pack[anchor='w']
# Use ttk to add styling to button
style = ttk.Style[]
style.configure['TButton', bg='skyblue', fg='white']
# Create button that will call the method to display text and
# close the program
next_button = ttk.Button[self, text="Next", command=self.printResults]
next_button.pack[]
def printResults[self]:
"""Print the results of the checkboxes and radio buttons."""
for cb in self.foods_dict.values[]:
if cb.var.get[]:
print['Item selected: {}'.format[cb['text']]]
index = self.var.get[]
print["Payment method: {}".format[self.payment_methods[index]]]
self.quit[]
if __name__ == "__main__":
app = SimpleGUI[]
app.mainloop[]
6 được sử dụng để tạo từng phiên bản nút kiểm. Tham khảo mã để nhận xét về cách thiết lập tiện ích con Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
8. Các vật dụng tiếp theo chúng ta cần tạo là các nút radio. Bằng cách chia sẻ đối tượng Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
3, chúng tôi tạo ra một nhóm nút radio loại trừ lẫn nhau. Loại trừ lẫn nhau đề cập đến lý thuyết xác suất rằng hai hoặc nhiều sự kiện không thể xảy ra cùng một lúc. Cuối cùng, khi nhấp vào
Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
89 thì phương thức Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
90 được gọi. Điều này in văn bản từ các nút kiểm và nút radio đã chọn và đóng chương trìnhBản tóm tắt
Trong hướng dẫn này, chúng ta sẽ xem xét ngắn gọn các tiện ích
Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
8 và Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
9. Hai loại vật dụng này rất hữu ích để cho phép người dùng chọn các lựa chọn từ một nhóm các tùy chọn. Các nút kiểm thường được sử dụng khi người dùng cần có thể chọn nhiều lựa chọn. Radiobuttons được sử dụng tốt nhất khi người dùng chỉ cần chọn một lựa chọn từ nhiều lựa chọnĐể biết thêm thông tin về Tkinter hoặc các tiện ích
Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
8 và Label[root, text="Select your country of birth: "].pack[anchor='w']
var1 = StringVar[root, "USA"] # Create a variable for strings, and initialize the variable
Radiobutton[root, text="USA", variable=var1, value="USA", command=printResults].pack[anchor='w']
Radiobutton[root, text="France", variable=var1, value="France", command=printResults].pack[anchor='w']
Radiobutton[root, text="Germany", variable=var1, value="Germany", command=printResults].pack[anchor='w']
Radiobutton[root, text="China", variable=var1, value="China", command=printResults].pack[anchor='w']
def printResults[]:
print[var1.get[]]
9, hãy xem tài liệu về Python trên Tkinter