首页 > 解决方案 > 检索 ttk.combobox 的选定值

问题描述

我正在创建一个用户界面,其中有一个第一个窗口,要求用户在选项列表中选择一个参数。这是一个 MWE:

from tkinter import *
import tkinter.ttk as ttk

Port=''
root = Tk()

PortCOM = ttk.Combobox(root, values=[1,2,3,4,5,6])
PortCOM.bind("<<ComboboxSelected>>",Port)
PortCOM.pack ()

root.mainloop()

print(Port)

所以我已经尝试过了,但也:

Port = PortCOM.get
Port = PortCOM.cget

通过最后一次尝试,我收到了错误消息:

<bound method Misc.cget of <tkinter.ttk.Combobox object .!combobox>>

例如,如果用户在我的值列表中选择值“4”,我希望它存储在变量“端口”中。

标签: python-3.xtkintercomboboxgetttk

解决方案


您不需要绑定来跟踪变量。您可以使用 StringVar 执行此操作。也就是说,您不能只是Port = PortCOM.get在启动代码时调用全局并期望得到任何东西。正确语法的第一个问题是Port = PortCOM.get()括号。第二,您get()在 init 处调用,因此如果不是错误,唯一可能的值将是一个空字符串。

我看到的下一个问题是,bind()这并没有按照您认为的那样做。绑定用于调用函数而不是直接更新变量。

的正确用法是根据值Combobox将 atextvariableIntVar()或一起使用,然后在函数中需要它时在该 var 上使用。StringVar()get()

from tkinter import *
import tkinter.ttk as ttk


root = Tk()

textVar = StringVar(root)
textVar.set('')
PortCOM = ttk.Combobox(root, textvariable=textVar, values=[1, 2, 3, 4, 5, 6])
PortCOM.pack()


def print_value():
    print(textVar.get())


Button(root, text='Print Value', command=print_value).pack()

root.mainloop()

如果您出于某种原因确实想使用bind(),例如让选择在选择时立即执行某些操作,请尝试使用此方法。

确保绑定调用在用于对组合框执行某些操作的函数之后。

from tkinter import *
import tkinter.ttk as ttk


root = Tk()

textVar = StringVar(root)
textVar.set('')
PortCOM = ttk.Combobox(root, textvariable=textVar, values=[1, 2, 3, 4, 5, 6])
PortCOM.pack()

# Note the _ in the argument section of the function.
# A bind will send an event to the function selected unless you use a lambda.
# so to deal with events we don't care about we have a few options.
# We can use an underscore to just except any argument and do nothing with it.
# We could also do event=None but typically I only use that when a function might use the event variable but not always.
def print_value(_): 
    print(textVar.get())
    print(PortCOM.get())


PortCOM.bind("<<ComboboxSelected>>", print_value)

root.mainloop()

推荐阅读