繁体   English   中英

Python Tkinter:将下拉菜单值解析为 function 作为变量?

[英]Python Tkinter: Parsing dropdown menu value into a function as a variable?

我正在尝试创建一个 Tkinter 下拉菜单以添加到主 GUI 中。 菜单的目的是给用户几个选项来选择图像分割神经网络(目前只有两个选项)。

我无法获取下拉菜单的值并通过 function 作为参数(变量,而不是字符串)解析它。

我尝试在 GUI window class 中创建一个staticmethod方法来搜索下拉菜单的值,并在按下 GUI 中的分段按钮时通过图像分割 function 解析该值。 分割 function 有两个参数netpath ,分别是神经网络和图像文件路径。

我不太确定如何更改变量的各个参数,所以我只是根据下拉菜单的值更改了整个变量。 唯一改变的是段 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM