如何更改self.button的状态

时间:2018-08-22 17:07:25

标签: python python-3.x oop tkinter

我尝试与Tkinter学习对象Oriendet。 我做了一个Button类并尝试使用它,但是我无法更改它的状态

这是我的课程

class Buton():
    def __init__(self, konum=None, text=None, command=None, cursor="hand2", state="normal", width=None,
                 row=None, column=None, sticky=None):
        print("SELF: ", type(self), self)
        self.konum = konum
        self.text = text
        self.command = command
        self.cursor = cursor
        self.state = state
        self.width = width
        self.row = row
        self.column = column
        self.sticky = sticky
        self.buton_bas()

    def buton_bas(self):
        self.buton = Button(self.konum, text=self.text, state=self.state, command=self.command)
        self.buton.grid(row=self.row, column=self.column, padx=2, pady=5)

    def state_change(self, new_state):
        self.['state'] = new_statew

我的定义和按钮

def print():
    global label
    label = Label(pencere, text=entry.get(), fg="lightgray", bg=darkbg, font=("Times 10"))
    label.grid(row=3, column=0, columnspan=2, padx=2, pady=5, )
    Buton.state_change(buton1, "disable")

buton1 = Buton(konum=pencere, text="Print", command=print, row=2, column=0)

当我按下“打印”按钮时,它将打印输入的文本。好的,但是我不能更改按钮的状态。我认为:TypeError:“ Buton”对象不支持项目分配

我尝试;

self.state = new_state

但是不工作..怎么了? 感谢您的帮助

1 个答案:

答案 0 :(得分:0)

您的代码包含很多错误。我已经解决了。您需要使用<button>["state"] = state。试试:

from tkinter import *
root = Tk()
class Buton():
    def __init__(self, konum=None, text=None, command=None, cursor="hand2", state="normal", width=None,
                 row=None, column=None, sticky=None):
        #print("SELF: ", type(self), self)
        self.konum = konum
        self.text = text
        self.command = command
        self.cursor = cursor
        self.state = state
        self.width = width
        self.row = row
        self.column = column
        self.sticky = sticky
        self.buton_bas()

    def buton_bas(self):
        self.buton = Button(self.konum, text=self.text, state=self.state, command=self.command)
        self.buton.grid(row=self.row, column=self.column, padx=2, pady=5)

    def state_change(self, new_state):
        self.buton['state'] = new_state
def print():
    global label
    label = Label(root, text="You can change text", fg="lightgray", bg="grey", font=("Times 10"))
    label.grid(row=3, column=0, columnspan=2, padx=2, pady=5, )
    Buton.state_change(buton1, "disable")

buton1 = Buton(konum=root, text="Print", command=print, row=2, column=0)