[英]Python Tkinter: Parsing dropdown menu value into a function as a variable?
我正在嘗試創建一個 Tkinter 下拉菜單以添加到主 GUI 中。 菜單的目的是給用戶幾個選項來選擇圖像分割神經網絡(目前只有兩個選項)。
我無法獲取下拉菜單的值並通過 function 作為參數(變量,而不是字符串)解析它。
我嘗試在 GUI window class 中創建一個staticmethod
方法來搜索下拉菜單的值,並在按下 GUI 中的分段按鈕時通過圖像分割 function 解析該值。 分割 function 有兩個參數net
和path
,分別是神經網絡和圖像文件路徑。
我不太確定如何更改變量的各個參數,所以我只是根據下拉菜單的值更改了整個變量。 唯一改變的是段 function 綁定到 Tkinter 按鈕的net
參數。
編碼:
@staticmethod
def find_option():
if menu1.get() == "fcn":
App.btn2 = Button(App.btn_frame, text="Segment", width = 10, height = 1, cursor = "hand2", command=lambda: App.segment(net=App.fcn, path=App.path))
else:
App.btn2 = btn2 = Button(App.btn_frame, text="Segment", width = 10, height = 1, cursor = "hand2", command=lambda: App.segment(net=App.dlab, path=App.path))
下拉菜單代碼:
fcn = models.segmentation.fcn_resnet101(pretrained=True).eval()
dlab = models.segmentation.deeplabv3_resnet101(pretrained=1).eval()
options = ["fcn", "dlab"]
variable = StringVar(btn_frame)
variable.set(options[0]) # default value
menu1 = OptionMenu(btn_frame, variable, *options)
menu1.pack(side=LEFT)
btn_frame
是包含按鈕的主 window 內的框架。
App
是主GUI class。 menu1
需要被引用為App.menu1
但由於某種原因,它會導致幾個錯誤(其他 class 變量將變得undefined
,並且會說App object has no attribute menu
)。 我還嘗試將menu1
引用為App().menu1
但每次按下分段按鈕時都會啟動一個新的 window ,而且它實際上從未顯示分段圖像。
編輯:我想你想要這樣的東西。 很難知道我什么時候看不到整個代碼,但可能是你忘記了通過find_option
方法傳遞self
嗎?
# This is the option menu part
self.options = ["fcn", "dlab"]
self.variable = tk.StringVar(btn_frame)
self.variable.set(options[0]) # default value
self.menu1 = tk.OptionMenu(
btn_frame, self.variable, *self.options)
self.menu1.pack(side=LEFT)
# And then later you have this method (remember to pass self to find_option)
def find_option(self):
if self.variable.get() == "fcn":
# your code
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.