检索和使用tkinter组合框选择

2024-10-01 15:44:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为一个自定义计算器组合一个GUI,它可以自动将某些度量单位转换为其他度量单位。在

我想返回所选的实际文本,这样我就可以从用户选择的任何内容编写if语句。如何让python返回实际值而不是现在得到的值?在

每当我测试此代码时,我会收到以下信息:

虚拟事件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新手,所以如果这只是我所缺少的一个简单语法,我一点也不会感到惊讶。在


Tags: 代码用户importmaster内容if度量tkinter
3条回答

您应该使用get()函数检索comboARU的内容,如下所示:

def callback(eventObject):
    print(comboARU.get())

您可以直接从事件对象中检索组合框的值 通过事件对象.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()

如果您希望能够使用与comboAru.current(0)一起设置的默认值,那么事件处理不起作用,我发现在按OK按钮时获取组合框值是最有效的方法,如果您想获得该值并在以后使用它,最好创建一个类,避免全局变量(因为类实例及其变量在tkinter窗口被破坏)(基于答案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())

相关问题 更多 >

    热门问题