python-3.x - 检索 ttk.combobox 的选定值

标签 python-3.x tkinter combobox get ttk

我正在创建一个用户界面,其中有一个第一个窗口,要求用户在选项列表中选择一个参数。这是一个 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”,我希望将其存储在变量“Port”中。

最佳答案

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

我看到的下一个问题是 bind() 它没有按照您认为的方式执行操作。绑定(bind)用于调用函数,而不是直接更新变量。

Combobox 的正确用法是将 textvariableIntVar()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(),例如让选择在选择时立即执行某些操作,请尝试此操作。

确保绑定(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()

关于python-3.x - 检索 ttk.combobox 的选定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57853537/

相关文章:

python - 如何同时给图片添加对比度、亮度等多种效果

python - 如何在 tkinter 中更新文本标签?

mysql - Visual Studio 2015 组合框

javascript - 使用python获取空白电子邮件

Python GUI(tkinter;pygtk+glade),py2exe

java - `AutoFillTextBox type is not resolvable` 为什么?

javascript - ExtJs - Javascript - 网格中的组合框(单元格编辑插件) - 网格/窗口后面的下拉列表

python - 如何复制不是从数组中随机采样的值?

python - 变量未在 exec ('variable = value' 后定义)

python - 添加记录器导致can't pickle _thread.RLock objects错误