我有一个列出了汽车品牌的清单,还有一个列出了这些品牌的车型名称的清单。我想有两个下拉列表。首先选择品牌,然后在第二个下拉列表中选择型号。但是只是所选品牌的型号。我得到以下代码。
import tkinter as tk
brands = ["Bugatti","VW","Opel","Porsche"]
models = [["Veyron","Chiron"],
["Golf","Passat","Polo","Caddy"],
["Insignia","Corsa","Astra"],
["Taycan","Cayenne","911"]]
root = tk.Tk()
canvas = tk.Canvas(root, height=500, width= 500, bg="white")
canvas.pack()
tkvar = tk.StringVar(root)
tkvar.set('Choose')
popupMenu1 = OptionMenu(canvas, tkvar, *brands)
popupMenu1.pack()
def change_dropdown(*args):
print("Chosen brand " + tkvar.get())
for i in range(len(brands)):
if tkvar.get() == brands[i]:
print(models[i])
tkvar.trace('w', change_dropdown)
root.mainloop()
现在如何使用列表模型中的信息创建第二个下拉列表。感谢您的帮助。
答案 0 :(得分:1)
您可以使用组合框制作相关的下拉列表
import tkinter
from tkinter import ttk
root = tkinter.Tk()
'''
widgets are added here
'''
brands = ["Bugatti","VW","Opel","Porsche"]
models = [["Veyron","Chiron"],
["Golf","Passat","Polo","Caddy"],
["Insignia","Corsa","Astra"],
["Taycan","Cayenne","911"]]
car_brand = ttk.Combobox(root, width=37, value=(brands))
car_brand.grid(row=3, column=1, columnspan=2, padx=10, pady=2, sticky='w')
def callback(eventObject):
abc = eventObject.widget.get()
car = car_brand.get()
index=brands.index(car)
car_model.config(values=models[index])
car_model = ttk.Combobox(root, width=37)
car_model.grid(row=4, column=1, columnspan=2, padx=10, pady=2, sticky='w')
car_model.bind('<Button-1>', callback)
root.mainloop()
答案 1 :(得分:0)
import tkinter as tk
brands = ["Bugatti","VW","Opel","Porsche"]
models = [["Veyron","Chiron"],
["Golf","Passat","Polo","Caddy"],
["Insignia","Corsa","Astra"],
["Taycan","Cayenne","911"]]
root = tk.Tk()
canvas = tk.Canvas(root, height=500, width= 500, bg="white")
canvas.pack()
tkvar = tk.StringVar(root)
tkvar.set('Choose')
tkvar2 = tk.StringVar(root)
tkvar2.set('Model')
popupMenu1 = tk.OptionMenu(canvas, tkvar, *brands)
popupMenu1.pack()
popupMenu2 = tk.OptionMenu(canvas, tkvar2, [])
popupMenu2.pack()
def change_dropdown(*args):
print("Chosen brand " + tkvar.get())
for i in range(len(brands)):
if tkvar.get() == brands[i]:
popupMenu2["menu"].delete(0, "end")
for item in models[i]:
popupMenu2['menu'].add_command(label=item, command=tk._setit(tkvar2, item))
tkvar.trace('w', change_dropdown)
root.mainloop()