使用第二个按钮更改按钮状态

时间:2019-10-10 06:41:43

标签: python python-3.x tkinter

我想通过按下另一个按钮将一个按钮的状态更改为NORMAL。

import tkinter as tk
from tkinter import ttk, StringVar
from tkinter.constants import DISABLED

LARGE_FONT =('Verdana',12)

class Auswertung(tk.Tk):

    def __init__(self,*args, **kwargs):

        tk.Tk.__init__(self,*args,**kwargs)
        container = tk.Frame(self)
        container.grid(row=0, column=1, padx=10, pady=10)

        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (Datenwahl,):
            frame = F(container,self)

            self.frames[F] = frame

            frame.grid(row=0, column=0, sticky='nsew')

        self.show_frame(Datenwahl)

    def show_frame(self,cont):

        frame = self.frames [cont] 
        frame.tkraise() 

    def enable_button2(self):
        self.button2.config(sate = NORMAL)


class Datenwahl(tk.Frame):



    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent,)



        label=tk.Label(self, text='Start Page', font=LARGE_FONT)
        label.grid(row=0, column=1, padx=10, pady=10 ,sticky= 'ew')

        button1 = tk.Button(self, text= 'Visit Page 1', 
                            command= lambda : controller.enable_button2())
        button1.grid(row=1, column=1, padx=10, pady=10)

        button2 = tk.Button(self, text= 'Visit Page 2', state=DISABLED,
                            command= lambda : controller.show_frame(PageTwo))
        button2.grid(row=2, column=1, padx=10, pady=10)


app = Auswertung()
app.mainloop()

这是整个错误消息:

Traceback (most recent call last):
  File "C:\Users\pasca\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "C:\Users\pasca\OneDrive\Dokumente\Privat\Python lernen\nested\tested.py", line 50, in <lambda>
    command= lambda : controller.enable_button2())
  File "C:\Users\pasca\OneDrive\Dokumente\Privat\Python lernen\nested\tested.py", line 34, in enable_button2
    self.button2.config(sate = NORMAL)
  File "C:\Users\pasca\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 2101, in __getattr__
    return getattr(self.tk, attr)
AttributeError: '_tkinter.tkapp' object has no attribute 'button2'

我已经尝试了不同的方法来解决问题,但是大多数情况下它要么给出相同的错误,要么对按钮状态毫无作用。我很期待我们的帮助。

1 个答案:

答案 0 :(得分:0)

除了创建局部变量,您还需要通过添加button2使Datenwahl成为self的类属性:

class Datenwahl(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent,)
        ...
        self.button2 = tk.Button(self, text= 'Visit Page 2', state="disabled",
                            command= lambda : controller.show_frame(PageTwo))
        self.button2.grid(row=2, column=1, padx=10, pady=10)

然后,您可以在button2的实例中访问Auswertung

class Auswertung(tk.Tk):

    ...

    def enable_button2(self):
        self.frames[Datenwahl].button2.config(state = "normal")