python-3.x - 检索 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”,我希望它存储在变量“端口”中。
解决方案
您不需要绑定来跟踪变量。您可以使用 StringVar 执行此操作。也就是说,您不能只是Port = PortCOM.get
在启动代码时调用全局并期望得到任何东西。正确语法的第一个问题是Port = PortCOM.get()
括号。第二,您get()
在 init 处调用,因此如果不是错误,唯一可能的值将是一个空字符串。
我看到的下一个问题是,bind()
这并没有按照您认为的那样做。绑定用于调用函数而不是直接更新变量。
的正确用法是根据值Combobox
将 atextvariable
与IntVar()
或一起使用,然后在函数中需要它时在该 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()
推荐阅读
- android - 带有 RecyclerView 的 LinearLayout 在 CardView 外滚动时隐藏 ImageView
- apache-spark - 如何将聚合数据添加到 Apache Spark 中的原始数据集?
- php - 勾选表单上的复选框时PHP函数添加日期时间戳
- laravel - 将变量从组件传递到插槽
- android - Google 登录失败 error_description:"Invalid Value"
- excel - 使用执行 sql 任务创建具有多张工作表的 Excel
- python - 在 Windows 和 Unix 系统中执行符号链接时,sys.path 的填充方式有什么不同吗?
- apache-spark - 查找最新文件 pyspark
- google-sheets - 如何在谷歌电子表格中应用双重过滤器(水平+垂直)?
- javafx - setText() 在 start() 中与 FXML 一起使用时不起作用