如何更新组合框?

时间:2016-10-17 18:04:35

标签: python python-3.x user-interface tkinter combobox

# IMPORT MODULES -----------------------------------------------------------
from tkinter import *
from tkinter import Tk, StringVar, ttk

#---------------------------------------------------------------------------
# LISTS

以下是组合框中使用的列表

BlankLines = ["------------"]
CarBrandModel = ["------------","Audi", "BMW", "Mercedes"]
AudiModels = ["------------", "A4", "A8", "Q7", "R8"]
#----------------------------------------------------------------------------------
#FUNCTIONS

def ModelSelectionFunction():

    CarBrandModelSelected = Var1.get()
    print(CarBrandModelSelected)

这里它从组合框中获取值,但我的问题是当我从组合框中选择其他内容时它不会更新

    if CarBrandModelSelected == "------------":
        CarModelBox["value"] = BlankLines
        CarModelBox.current(0)

    elif CarBrandModelSelected == "Audi":
        CarModelBox["value"] = AudiModels
        CarModelBox.current(0)

# SET SCREEN ---------------------------------------------------------------
root = Tk()
root.geometry("1350x750")
root.title("Car Showroom System")
root.configure(bg="white")

#--------------------------------------------------------------------------
# VAR
Var1 = StringVar()
Var2 = StringVar()

此处存储字符串变量

#---------------------------------------------- -----------------------------

# SELECTION
SelectionFrame.grid_propagate(False)

CarBrand = Label(SelectionFrame, text="Car :")
CarBrand.grid(row=0, column=0)
CarBrandBox = ttk.Combobox(SelectionFrame, textvariable=Var1, state="readonly")
CarBrandBox.bind("<<ComboboxSelected>>")
CarBrandBox["value"] = CarBrandModel
CarBrandBox.current(0)
CarBrandBox.grid(row=0, column=1)



CarModel = Label(SelectionFrame, text="Model :")
CarModel.grid(row=1, column=0)
CarModelBox = ttk.Combobox(SelectionFrame, textvariable=Var2, state="readonly")
CarModelBox.grid(row=1, column=1)
ModelSelectionFunction()

调用该函数以决定放入组合框的内容

  root.mainloop()

1 个答案:

答案 0 :(得分:0)

您必须添加函数名称以绑定

CarBrandBox.bind("<<ComboboxSelected>>", ModelSelectionFunction)

并且当您在组合框中选择时,tkinter会执行它。

因为tkinter向绑定函数发送额外参数,所以您需要在函数中接收它。我添加=None,这样你仍然可以不带参数执行它。

def ModelSelectionFunction(event=None)

顺便说一句:这个论点可以给你选择值

if event:
    print(event.widget.get())