[英]Update optionmenu dynamically tkinter
我正在嘗試使用 tkinter 讀取.xlsx 工作表。 但代碼發布錯誤“TypeError:'NoneType' object 不可訂閱”。 我已經對其進行了足夠的試驗,但無法理解代碼的問題。
import openpyxl
from tkinter import filedialog
from tkinter import *
class data:
def __init__(self,master):
self.master = master
master.title("App")
master.geometry("600x200")
master.resizable(0,0)
x,y = 30,20
self.options = ['A',"B"]
self.om_variable = StringVar()
# self.om_variable.set(self.options[0])
# self.om_variable.trace('w', self.option_select)
self.om = OptionMenu(self.master, self.om_variable, *self.options).place(x = x+300,y = y+80)
Brw_2 = Button(master = self.master, text = 'Browse', width = 6, command=self.update_option_menu).place(x = x+500,y = y+40)
def update_option_menu(self):
self.om_variable.set('')
self.om["menu"].delete(0, "end")
xyx = self.get_SheetsName(r"C:\_Code\Inputs\SomeExcelFile.xlsx")
print("---->",xyx)
for string in xyx:
self.om["menu"].add_command(label=string,
command=lambda value=string: self.om_variable.set(value))
def get_SheetsName(self, excel_file):
wb = openpyxl.load_workbook(excel_file)
SH_lst = wb.sheetnames
Sh_names = [sh for sh in SH_lst if "AllTags" in sh]
return Sh_names
root = Tk()
myGui = data(root)
root.mainloop()
這是一個常見的錯誤。 當你寫這個:
self.om = OptionMenu(self.master, self.om_variable, *self.options).place(x = x+300,y = y+80)
Python 創建了一個選項菜單,然后調用.place()
方法。 None
的結果被保存到self.om
。 您想要的是創建選項菜單,然后將其存儲在self.om
中,然后使用.place()
放置
所以你基本上 python 是這樣解釋的:
temp_var = OptionMenu(self.master, self.om_variable, *self.options)
self.om = temp_var .place(x = x+300,y = y+80)
del temp_var
你應該寫的是:
self.om = OptionMenu(self.master, self.om_variable, *self.options)
self.om.place(x = x+300,y = y+80)
提示:在沒有將 object 保存到變量的情況下,切勿在調用構造函數后直接調用grid
/ place
/ pack
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.