0

我正在尝试使使用 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)

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

4

1 回答 1

0

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

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()
于 2018-05-26T03:50:31.177 回答