簡體   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