就像在一个下拉列表中包含大陆名称并显示与所选大陆相关的国家/地区名称的著名示例一样。如何使用 Tkinter 实现这一点? 我在第一个下拉列表中列出了大陆列表,并在列表中列出了与大陆相关的所有国家/地区。我想在选择 Continental_1 时显示 Country_11、Country_12,其他大陆也类似。
这是我正在处理的代码 -
import tkinter as tk
from tkinter import ttk
from tkinter import *
root = tk.Tk()
root.geometry('500x500')
#Label to Continent
label_1 = tk.Label(root, text="Select the Continent", font = (8), bg = '#ffe1c4')
label_1.place(x = 120, y = 220)
# Continent selection - drop down
optionList1 = ["Continent1", "Continent2","Continent3"]
dropVar1 = StringVar()
dropMenu1 = ttk.OptionMenu(root, dropVar1 , *optionList1)
dropMenu1.place(x = 300, y = 220)
#Label to Select Country
label_2 = tk.Label(root, text="Select the Country ", font = (8), bg = '#ffe1c4')
label_2.place(x = 120, y = 250)
# Country name selection - drop down
optionList2 = ["Country_11", "Country_12", "Country_21","Country_22","Country_31","Country_32"]
dropVar2 = StringVar()
dropMenu2 = ttk.OptionMenu(root, dropVar2, *optionList2)
dropMenu2.place(x = 300, y = 250)
root.mainloop()
如果有一个解决方案就好了,因为我不知道 OptionMenu 在 Tkinter 中可以拥有的所有属性。 提前致谢!!
最佳答案
如果您的意思是创建两个OptionMenu
,当在第一个下拉菜单中选择不同的值时,它将显示不同的值。
你可以试试这个:
import tkinter as tk
from tkinter import ttk
from tkinter import *
def func(selected_value): # the selected_value is the value you selected in the first drop down menu.
dropMenu2.set_menu(*optionList2.get(selected_value))
root = tk.Tk()
root.geometry('500x500')
#Label to Continent
label_1 = tk.Label(root, text="Select the Continent", font = (8), bg = '#ffe1c4')
label_1.place(x = 120, y = 220)
# Continent selection - drop down
optionList1 = ["-","Continent1", "Continent2","Continent3"]
dropVar1 = StringVar()
dropMenu1 = ttk.OptionMenu(root, dropVar1 , *optionList1,command=func) # bind a command for the first dropmenu
dropMenu1.place(x = 300, y = 220)
#Label to Select Country
label_2 = tk.Label(root, text="Select the Country ", font = (8), bg = '#ffe1c4')
label_2.place(x = 120, y = 250)
# Country name selection - drop down
optionList2 = { # when select different value,show the list.
"Continent1": ["Country_11", "Country_12"],
"Continent2": ["Country_21", "Country_22"],
"Continent3": ["Country_31", "Country_32"]
}
dropVar2 = StringVar()
dropMenu2 = ttk.OptionMenu(root, dropVar2, "-")
dropMenu2.place(x = 300, y = 250)
root.mainloop()
(建议:ttk.Combobox
比 OptionMenu
更漂亮,并且使用 from tkinter import *
不是一个好的做法。)
关于python - 我们可以在 tkinter 中嵌套两个 OptionMenu 小部件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61026521/