我在我的tkinter視窗中有一個menu標簽,當我按下Upload months選項時,它會呼叫upload_months函式,然后出現一個OptionMenu和一個按鈕。
我只是希望每次我按下那個按鈕都能得到OptionMenu中的選項,即使它改變了它的選項。
我的代碼是:
from tkinter import *
root = Tk()
root.geometry('300x300')
menubar = Menu(root)
root.config(menu=menubar)
def upload_months() 。
months = ["January", "Feb","Mar"]
變數 = StringVar(root)
variable.set('Choose')
w = OptionMenu(root, variable, *months, command=callback)
B = Button(root, text ="發送", command = get_optionMenu_selection)
w.place(x=20, y=10)
B.place(x=105, y=11)
def callback(selection)。
return選擇。
def get_optionMenu_selection():
value = callback(None)
print(value)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Upload months", command=upload_months)
filemenu.add_command(label="Open")
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
root.mainloop()
在callback()中,我試圖回傳OptionMenu的值,所以它可以在get_optionMenu_selection()中被接收并保存到value中,所以我可以每次都列印value,但是它不起作用。
我的視窗看起來像這樣:
而且每次我按下Send時,我都想得到文本,所以在控制臺中看起來像這樣:
January
二月
3月
3月
一月
...
相反,每次我按下Send時,我只是在控制臺中得到:
None。
None。
...
uj5u.com熱心網友回復:
這是錯誤的來源:
這是錯誤的來源。
def get_optionMenu_selection():
value = callback(None) ### this returns Noneprint(value)
事實上,你不需要回呼函式,因為你使用的是一個按鈕。你只需要把變數傳給get_optionMenu_selection函式。
from tkinter import *
from functools import partial
root = Tk()
root.geometry('300x300')
menubar = Menu(root)
root.config(menu=menubar)
###另一個函式被移除。
def get_optionMenu_selection(variable)。###this changed。
print(variable.get())
def upload_months()。
months = ["January", "Feb","Mar"]
變數 = StringVar(root)
variable.set('Choose')
w = OptionMenu(root, variable, *months)
B = Button(root, text ="Send", command = partial(get_optionMenu_selection, variable) ###this changed[/span]。
w.place(x=20, y=10)
B.place(x=105, y=11)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Upload months", command=upload_months)
filemenu.add_command(label="Open")
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
root.mainloop()
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/330585.html
標籤:
