我正在为一个定制的计算器组装一个GUI,它可以自动将某些度量单位转换为其他度量单位。
我想要返回实际选择的文本,这样我就可以从用户选择的任何内容中编写if语句。如何让python返回实际的值而不是我现在得到的值?
每当我测试这段代码时,我都会收到以下信息:
VirtualEvent event x=0 y=0
下面是我尝试用于此过程的代码部分。对于下面的示例代码,我希望用户能够输入英亩或平方英尺的面积。然后,我计划编写一个if语句,将他们选择的任何内容转换为平方千米(为了保持本文的简洁性,输入本例中未包含的数字的代码)。
import tkinter as tk
from tkinter.ttk import *
master = tk.Tk()
master.title("Gas Calculator")
v = tk.IntVar()
combo = Combobox(master)
def callback(eventObject):
print(eventObject)
comboARU = Combobox(master)
comboARU['values']= ("Acres", "Ft^2")
comboARU.current(0) #set the selected item
comboARU.grid(row=3, column=2)
comboARU.bind("<<ComboboxSelected>>", callback)
master.mainloop()如果有什么我可以扩展的,请告诉我。我仍然是python的新手,所以如果这只是我遗漏的一个简单的语法问题,我一点也不会感到惊讶。
发布于 2018-05-18 12:06:04
您应该使用get()函数检索comboARU的内容,如下所示:
def callback(eventObject):
print(comboARU.get())发布于 2018-05-18 14:31:03
您可以通过eventObject.widget.get()直接从事件对象检索组合框的值。
import tkinter as tk
from tkinter.ttk import *
master = tk.Tk()
master.title("Gas Calculator")
v = tk.IntVar()
combo = Combobox(master)
def callback(eventObject):
# you can also get the value off the eventObject
print(eventObject.widget.get())
# to see other information also available on the eventObject
print(dir(eventObject))
comboARU = Combobox(master)
comboARU['values']= ("Acres", "Ft^2")
comboARU.current(0) #set the selected item
comboARU.grid(row=3, column=2)
comboARU.bind("<<ComboboxSelected>>", callback)
master.mainloop()发布于 2019-10-01 00:30:57
如果你希望get能够使用comboAru.current(0)设置的默认值,事件处理不起作用,我发现当按下OK按钮时获得组合框的值是最好的,如果你想获得值并在以后使用它,最好创建一个类,避免全局变量(因为类实例和它的变量在tkinter窗口被销毁后仍然存在)(基于answer https://stackoverflow.com/a/49036760/12141765)。
import tkinter as tk # Python 3.x
from tkinter import ttk
class ComboboxSelectionWindow():
def __init__(self, master):
self.master=master
self.entry_contents=None
self.labelTop = tk.Label(master,text = "Select one of the following")
self.labelTop.place(x = 20, y = 10, width=140, height=10)
self.comboBox_example = ttk.Combobox(master,values=["Choice 1","Second choice","Something","Else"])
self.comboBox_example.current(0)
self.comboBox_example.place(x = 20, y = 30, width=140, height=25)
self.okButton = tk.Button(master, text='OK',command = self.callback)
self.okButton.place(x = 20, y = 60, width=140, height=25)
def callback(self):
""" get the contents of the Entry and exit
"""
self.comboBox_example_contents=self.comboBox_example.get()
self.master.destroy()
def ComboboxSelection():
app = tk.Tk()
app.geometry('180x100')
Selection=ComboboxSelectionWindow(app)
app.mainloop()
print("Selected interface: ", Selection.comboBox_example_contents)
return Selection.comboBox_example_contents
print("Tkinter combobox text selected =", ComboboxSelection())https://stackoverflow.com/questions/50402895
复制相似问题