繁体   English   中英

将组合框中选择的选项设置为一个变量,该变量随组合框中选择的选项而变化

[英]Setting an option selected in a combobox as a variable that changes as the option selected in the combobox does

我试图将在组合框的下拉列表中选择的选项设置为变量,但是,我用来表示变量的标签当前仅读取。!combobox。 例如,如果我从下拉菜单中选择“客户2”,则标签将更改为客户2。我可能需要使用按钮来执行此操作,但是我不确定如何使它工作。

import tkinter as tk
from tkinter import ttk
root = tk.Tk()

ICus = tk.StringVar(root)

ICus.set("Select Customer")

ICustomer = ttk.Combobox( textvariable = ICus, state = 'readonly')
ICustomer['values'] = ("Customer1", "Customer2", "Customer3")
ICustomer.grid(row = 2, column = 2)


label_ICustVar = tk.Label( text= ICustomer)
label_ICustVar.grid(row = 3, column = 3)

简而言之,我希望将下拉列表中选择的选项设置为变量,以便以后在代码中使用。 我是编码的新手,所以我可能会缺少一些明显的东西,任何帮助将不胜感激:)

我认为您最好使用a_guest提供的链接,但是对于您的示例,我认为最好使用标签的关键字textvariable,即

# note that this is the StringVar ICUS, not the combobox ICUSTOMER.
label_ICustVar = tk.Label( textvariable= ICus) 
label_ICustVar.grid(row = 3, column = 3)

您可以将<<ComboboxSelected>>事件与get()方法一起使用。

def update_label(event):
    label_ICustVar.configure(text=ICustomer.get())


ICustomer.bind("<<ComboboxSelected>>", update_label)

每次您从组合框下拉列表中选择一项时,都会触发update_label方法。

此方法不需要使用StringVar() ,因此可以删除ICus

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM