代码之家  ›  专栏  ›  技术社区  ›  Nguyen Ma

Python-tkinter组合框保存值

  •  1
  • Nguyen Ma  · 技术社区  · 7 年前

    我试图用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”存储在一个变量中,并在以后的代码中使用。 我试图在这里搜索,但所有的情况都只是打印一个值。我不想打印,我想存储一个值。

    有什么想法吗?

    非常感谢。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Mike - SMT    7 年前

    要实现您想要实现的目标,我们可以使用 bind() 方法和 get() 方法

    我注意到您在注释部分的代码中(看起来它现在已被删除)尝试执行以下操作 c = cbox.get() 但是,不会更新此值,因为它只在程序初始化时调用一次。相反,我们可以使用 cbox.get() 直接在我们的 if 语句,然后将该值赋给全局变量 c

    我们需要一个函数,该函数可以在选择组合框中的项目时触发所选事件时调用。我们可以指定一个函数,以便在使用 绑定() 方法

    我已经将您粘贴在注释中的代码重新格式化为功能性代码。

    更新时间:

    我添加了一个按钮来打印 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()