在tkinter的类中的函数之间传递变量:self.param vs param

时间:2019-03-01 04:23:53

标签: python function class tkinter self

在tkinter的同一类中的函数之间传递变量时,如果我只是传递变量,则它不起作用。如果该参数是实例变量,则该参数似乎仅在新函数中起作用。

我的代码是一个简单的窗口,如果输入字段不为空,则在按下按钮时会关闭。

class simpleGUI:
    def __init__(self, root):
        height = StringVar()
        self.root = root
        self.frame = ttk.Frame(self.root, padding='30 30 30 30')
        self.frame.grid(row=0, column=0, sticky=(N, W, E, S))
        self.root.title("Enter your parameters")
        ttk.Label(self.frame, text="Height").grid(row=1, column=1, sticky=(W, E))

        # widgets
        self.height = ttk.Entry(self.frame, width=7, textvariable=height)
        self.height.grid(row=2, column=1, sticky=(W, E))
        self.height.focus()

        self.button = ttk.Button(self.frame, text="OK", command=self.close_window)
        self.button.grid(row=3, column=1, sticky=(W, E))

    def close_window(self):
        if len(self.height.get())>0:
            self.root.destroy()

仅当高度小部件保存在self.height中时,此方法才有效。如果将self.height替换为height,则它将不起作用。 例如,如果代码的下半部分被以下内容代替:

        # widgets 
        height = ttk.Entry(self.frame, width=7, textvariable=Height)
        height.grid(row=2, column=1, sticky=(W, E))
        height.focus()

        self.button = ttk.Button(self.frame, text="OK", command=self.close_window(height))
        self.button.grid(row=3, column=1, sticky=(W, E))

    def close_window(self, height):
        if len(height.get())>0:
            self.root.destroy()

我在控制台中没有任何错误它只是不再关闭窗口了,我试图理解为什么。来自经验丰富的人们的建议将不胜感激。

0 个答案:

没有答案