在tkinter中将过程转换为OO的问题

问题描述 投票:0回答:1

我以程序方式使用tkinter编写了一个脚本,该脚本可以正常工作:

import tkinter as tk

master = tk.Tk()

Experiment = tk.StringVar()

list1 = ['Option 1', 'Option 2', 'Option 3', 'Custom...']

def new_label(Experiment):
    if (Experiment == 'Custom...'):
        label_6 = tk.Label(master,
              text='Experiment',
              relief = 'solid',
              width=20,
              font=('arial',10,'bold')).pack()
Experiment.set('Experiment')
droplist = tk.OptionMenu(master, Experiment, *list1, command = new_label)

droplist.config(width=20)
droplist.pack()

master.mainloop()

但是,当我尝试使用面向对象的方法时:

import tkinter as tk


class demo1:
    def __init__(self, master):
        self.master = master
        self.Experiment = tk.StringVar()

        self.Experiment.set('Experiment')
        list1 = ['Option 1', 'Option 2', 'Option 3', 'Custom...']
        self.droplist = tk.OptionMenu(self.master, self.Experiment, *list1, command = self.new_label)

        self.droplist.config(width=20)
        self.droplist.pack()

    def new_label(self):
        if (self.Experiment == 'Custom...'):
            label_6 = tk.Label(self.master,
                  text='Experiment',
                  relief = 'solid',
                  width=20,
                  font=('arial',10,'bold')).pack()

root = tk.Tk()
app = demo1(root)
root.mainloop()

我遇到此错误:

Tkinter回调Traceback中的异常(最近一次调用为:):文件“ /home/majido/anaconda3/lib/python3.7/tkinter/init.py”,行1705,在call中返回self.func(* args)文件“ /home/majido/anaconda3/lib/python3.7/tkinter/init.py”,行3442,在call中self .__ callback(self .__ value,* args)TypeError:new_label()接受1个位置参数,但给出了2个]

我无法将其与已经编码的内容联系起来,我没有传递任何东西。

python oop tkinter
1个回答
0
投票

OptionMenucommand回调收到用户选择的选项,您的方法不会使用此选项(它仅使用隐式的self)。请注意,在您的第一个版本中,该函数如何采用Experiment,但在第二个版本中却没有。您至少需要添加一个虚拟参数,以便new_label回调采用正确数量的参数:

def new_label(self, _):  # An "unnamed" parameter to handle the unneeded data given to the callback
    . . .

或者,只需创建一个包装函数,为您抛出传递的参数:

. . . command = lambda _: self.new_label())
© www.soinside.com 2019 - 2024. All rights reserved.