在下面的代碼中,我有兩個選項選單,它們填充了相同的串列。在最終應用程式中,串列是通過匯入 .csv 檔案生成的。
用戶應該能夠從串列中選擇兩個條目。
現在的問題是,更改第一個選項選單將更改第二個選項選單。但是,第二個按預期作業。
我猜這個函式update_file_list_selection()和lambda函式實作得很糟糕。
import tkinter as tk
from tkinter import ttk
class File_Selection():
def __init__(self, frame, text):
self.frame = frame
self.text = text
self.label_file = tk.Label(self.frame, text=text)
self.label_file.pack()
self.variable_file = tk.StringVar(self.frame)
self.option_list = ["no file loaded"]
self.variable_file.set(self.option_list[0])
self.optionmenu_file = tk.OptionMenu(self.frame, self.variable_file,
*self.option_list)
self.optionmenu_file.pack()
class View:
def __init__(self, view, update_list):
self.view = view
self.view.title("Test")
self.view.geometry("320x240")
self.view.resizable(False, False)
self.frame = tk.Frame(self.view)
self.frame.pack()
self.button = tk.Button(self.frame, text="Update", command=update_list)
self.button.pack()
self.file_one = File_Selection(self.frame, "File 1")
self.file_two = File_Selection(self.frame, "File 2")
class Controller:
def __init__(self):
self.root = tk.Tk()
self.view = View(self.root, lambda: self.update_file_list_selection())
self.files = ["File 1", "File 2", "File 3", "File 4"]
def run(self):
self.root.mainloop()
def update_file_list_selection(self):
self.active_file_selection = [self.view.file_one, self.view.file_two]
for file_selection in self.active_file_selection:
self.menu = file_selection.optionmenu_file["menu"]
self.menu.delete(0, "end")
for x in self.files:
file_selection.option_list.append(x)
self.menu.add_command(label=x,
command=lambda value=x: file_selection.variable_file.set(value))
file_selection.variable_file.set(self.files[0])
if __name__ == "__main__":
c = Controller()
c.run()
uj5u.com熱心網友回復:
我猜函式 update_file_list_selection() 和 lambda 函式實作得很糟糕。
這是一個正確的猜測。
原因是使用的一個常見問題lambda- 當你這樣做時command=lambda value=x: file_selection.variable_file.set(value), 的值file_selection不會是回圈中的值,它最終會成為最后一次設定該變數的值。您可以通過將值系結到lambda作為默認引數來解決此問題:
self.menu.add_command(label=x, command=lambda value=x, fs=file_selection: fs.variable_file.set(value))
以上將確保在lambda正文內部,fs將設定為創建file_selection選單項時的值,而不是選擇項時的值。
您最終仍然會OptionMenu得到與普通OptionMenu專案不完全相同的專案,但在這個特定的示例中,這似乎并不重要,因為您沒有command與OptionMenu整體關聯。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/407815.html
標籤:
下一篇:創建多個標簽
