就像著名的示例一样,在一个下拉列表中具有大洲名称,并显示与所选大洲相关的国家/地区名称。如何使用Tkinter实现呢?
我在第一个下拉列表中有“大陆列表”,并且在列表中列出了与各大洲相关的所有国家。当选择continent_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()

现在它是:
python - 我们可以在tkinter中嵌套两个OptionMenu小部件吗?-LMLPHP
选择其他值时:
python - 我们可以在tkinter中嵌套两个OptionMenu小部件吗?-LMLPHP
(建议:ttk.ComboboxOptionMenu漂亮,并且使用from tkinter import *不是一个好习惯。)

关于python - 我们可以在tkinter中嵌套两个OptionMenu小部件吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61026521/

10-12 22:15