[英]Creating a choicelist dialog box with tkinter
我正在嘗試使用 tkinter a function 類似於 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)
它創建了一個 window 和 label、選擇列表和按鈕,但是當按下“完成”按鈕時它不返回所選項目。 我怎樣才能使這項工作?
微小的修改將使它像你想要的那樣工作。 結果是由按鈕 function 返回的,而不是由外部 function 返回的。通過在您的 function 中使其成為全局,外部 function 能夠返回它。 注意:您還必須跳出主循環,以便外部 function 完成:
from tkinter import *
def mychoicebox(choicelist):
global result
def buttonfn():
global result
result = var.get()
choicewin.quit()
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()
return result
# Testing:
reply = mychoicebox(["one", "two", "three"])
print("reply:", reply)
它有點重新布置成一類,但這是您想要做的嗎?
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.