我正在尝试使用 tkinter 制作一个组合框,示例如下
import tkinter as tk
from tkinter import ttk
tkwindow = tk.Tk()
cbox = ttk.Combobox(tkwindow, values=['2.4', '5'], state='readonly')
cbox.grid(column=0, row=0)
tkwindow.mainloop()
我希望当我从组合框中选择一个选项时,假设我选择“2.4”。然后我可以将“2.4”存储在变量中并稍后在我的代码中使用。 我尝试在这里搜索,但所有情况都只是打印一个值。我不想打印,我想存储一个值。
对此有什么想法吗?
谢谢。
最佳答案
为了完成您想要完成的任务,我们可以使用 bind()
方法和 get()
方法。
我在评论部分的代码中注意到(看起来现在已被删除),您尝试执行 c = cbox.get()
但是该值没有被更新,因为它只被调用一旦你的程序初始化。相反,我们可以直接在 if
语句中使用 cbox.get()
,然后将该值分配给全局变量 c
。
我们需要一个可以在选择组合框中的项目期间触发 Selected 事件时调用的函数。我们可以指定一个函数,以便在使用 bind()
方法触发此事件时调用。
我已将您粘贴在评论中的代码重新格式化为实用的代码。
更新:
我添加了一个按钮来打印 c
当前存储的值,以便您可以在每次从组合框中选择后检查该值。
请参阅下面的代码。
import tkinter as tk
from tkinter import ttk
tkwindow = tk.Tk()
c = ""
# This function will check the current value of cbox and then set
# that value to the global variable c.
def check_cbox(event):
global c
if cbox.get() == '2.4':
c = cbox.get() # this will assign the variable c the value of cbox
if cbox.get() == '5':
c = cbox.get()
def print_c_current_value():
print(c)
cbox = ttk.Combobox(tkwindow, values=['2.4', '5'], state='readonly')
cbox.grid(column=0, row=0)
# This bind calls the check_box() function when an item is selected.
cbox.bind("<<ComboboxSelected>>", check_cbox)
tk.Button(tkwindow, text="Print C", command=print_c_current_value).grid(column=0, row=1)
tkwindow.mainloop()
关于Python-tkinter组合框保存值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49496295/