这是我在Tkinter的ComboBox。当我想从此组合框中选择某项时,什么也没有发生。我看到了光标从数据库中选择的所有选项,但我会说它是“只读的”。为了进行测试,我写了一个if语句来确保这一点,但是不幸的是,消息框没有出现。我想我需要更多操作此组合框的信息,请帮助我。
var1 = StringVar()
lblChooseaModel = Label(bottomLeftTopR, font = ('arial', 12, 'bold'), text =
"Choose a model", fg = "black", width = 13, bd = 14, anchor = 'w')
lblChooseaModel.grid(row = 0, column = 0)
cboChooseaModel = ttk.Combobox(bottomLeftTopR, textvariable = var1, font =
('arial', 20, 'bold'), width = 12)
models_query = cur.execute('SELECT name_of_model FROM models')
data_models = ['']
for row in models_query:
data_models.append(row)
cboChooseaModel['value'] = data_models
cboChooseaModel.current(0)
cboChooseaModel.grid(row = 1, column = 0)
if cboChooseaModel.get() == (data_models[1]):
messagebox.showinfo("You chose Mazda 2")
当我打印“ data_models”时,我可以看到:
['',('马自达2'),('马自达3'),('马自达6'),('马自达CX 3'),('马自达CX 5')]
答案 0 :(得分:1)
将跟踪添加到组合框的StringVar:
#tkinter setup
from tkinter import *
import tkinter.ttk as ttk
from tkinter import messagebox
bottomLeftTopR = Tk()
def combo_choose(value):
messagebox.showinfo("Choice", "You Chose " + value)
var1 = StringVar()
lblChooseaModel = Label(bottomLeftTopR, font = ('arial', 12, 'bold'),text = "Choose a model",
fg = "black", width = 13, bd = 14, anchor = 'w')
lblChooseaModel.grid(row = 0, column = 0)
cboChooseaModel = ttk.Combobox(bottomLeftTopR, textvariable = var1,
font = ('arial', 20, 'bold'), width = 12)
#models_query = cur.execute('SELECT name_of_model FROM models')
#data_models = ['']
#for row in models_query:
# data_models.append(row)
# Replaced query with data
data_models = [ ' ', ('Mazda 2'), ('Mazda 3'), ('Mazda 6'), ('Mazda CX 3'), ('Mazda CX 5') ]
cboChooseaModel['value'] = data_models
cboChooseaModel.current(0)
cboChooseaModel.grid(row = 1, column = 0)
var1.trace('w', lambda name, index, mode: combo_choose(var1.get()))
您可以在combo_choose函数中使用选定的值执行任何操作。在此代码中,列表chosen
被传递给函数,并将值附加到列表中,然后打印该列表。
#tkinter setup
from tkinter import *
import tkinter.ttk as ttk
from tkinter import messagebox
bottomLeftTopR = Tk()
def combo_choose(chosen, value):
chosen.append(value)
print("You've chosen ", *chosen)
print(chosen)
var1 = StringVar()
lblChooseaModel = Label(bottomLeftTopR, font = ('arial', 12, 'bold'),text = "Choose a model",
fg = "black", width = 13, bd = 14, anchor = 'w')
lblChooseaModel.grid(row = 0, column = 0)
cboChooseaModel = ttk.Combobox(bottomLeftTopR, textvariable = var1,
font = ('arial', 20, 'bold'), width = 12)
#models_query = cur.execute('SELECT name_of_model FROM models')
#data_models = ['']
#for row in models_query:
# data_models.append(row)
# Replaced query with data
data_models = [ ' ', ('Mazda 2'), ('Mazda 3'), ('Mazda 6'), ('Mazda CX 3'), ('Mazda CX 5') ]
cboChooseaModel['value'] = data_models
cboChooseaModel.current(0)
cboChooseaModel.grid(row = 1, column = 0)
chosen = []
var1.trace('w', lambda name, index, mode: combo_choose(chosen, var1.get()))