Python-tkinter组合框保存值

标签 python tkinter combobox

我正在尝试使用 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/

相关文章:

python - Scrapy process_links 和 process_request 的示例代码

python - Pandas:如何更改列的所有值?

python - 我如何使用蓝图将所有路由拆分为子模块

mysql - 组合框并从数据网格显示

c++ - 在 MFC 中填充下拉列表

python - pyInstaller 多次加载脚本

python - Tkinter 添加标签框

python - Tkinter 应用程序在 Windows 上运行,但在树莓派上无法打开窗口

python - 在 Tkinter 中存储来自文本字段的输入

javascript - 组合框的 Onchange 事件不会发出任何警报