【问题标题】:Creating a choicelist dialog box with tkinter使用 tkinter 创建选择列表对话框
【发布时间】:2018-05-26 12:10:46
【问题描述】:

我正在尝试使用 tkinter 实现类似于 easygui (http://easygui.sourceforge.net/tutorial.html#buttonbox) 的按钮框的功能,我应该能够从控制台和 gui 应用程序中调用它:

from tkinter import *
def mychoicebox(choicelist): 
    def buttonfn(): 
        return var.get()
    choicewin = Tk()
    choicewin.resizable(False, False)
    choicewin.title("ChoiceBox")

    Label(choicewin, text="Select an item:").grid(row=0, column=0, sticky="W")

    var = StringVar(choicewin)
    var.set('No data') # default option
    popupMenu = OptionMenu(choicewin, var, *choicelist)
    popupMenu.grid(sticky=N+S+E+W, row =1, column = 0)

    Button(choicewin, text='Done', command=buttonfn).grid(row=2, column=0)
    choicewin.mainloop()

测试:

reply = mychoicebox(['one','two','three'])
print("reply:", reply)

它会创建一个带有标签、选择列表和按钮的窗口,但是当按下“完成”按钮时它不会返回所选项目。我怎样才能做到这一点?

【问题讨论】:

    标签: python user-interface tkinter dropdownchoice


    【解决方案1】:

    这有点重新排列成一个类,但这是你想要做的吗?

    from tkinter import *
    
    class Choices:
    
        def __init__(self, parent, choicelist):
    
            Label(choicewin, text="Select an item:").grid(row=0, column=0, sticky="W")
    
            self.var = StringVar()
            self.var.set('No data') # default option
            popupMenu = OptionMenu(choicewin, self.var, *choicelist)
            popupMenu.grid(sticky=N+S+E+W, row =1, column = 0)
    
            Button(choicewin, text='Done', command=self.buttonfn).grid(row=2, column=0)
    
        def buttonfn(self): 
            print(self.var.get())
    
    if __name__ == '__main__':
        choicewin = Tk()
        choicewin.resizable(False, False)
        choicewin.title("ChoiceBox")
        app = Choices(choicewin, ['one','two','three'])
        choicewin.mainloop()
    

    【讨论】:

    • class choices:下面应该有缩进
    • 好收获。固定的。最初有一些插入问题,但没有发现缩进混乱。
    • 这不返回一个值,它只打印它。这个问题似乎是关于从函数调用中返回值。
    • 是的,我想要一个简单的函数来显示一个选择框并返回选定的项目。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-07
    • 2012-07-18
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    • 2015-03-31
    • 2013-07-22
    相关资源
    最近更新 更多