【问题标题】:How to change state a self.button如何更改 self.button 的状态
【发布时间】:2018-08-22 17:07:25
【问题描述】:

我尝试使用 Tkinter 学习 Object Orientet。 我制作了一个按钮类并尝试使用它,但我无法更改它的状态

这是我的课

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 和按钮

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: 'Button' object does not support item assignment

我试试;

self.state = new_state

但不工作..有什么问题? 从现在开始感谢您的帮助

【问题讨论】:

  • 您有一个名为 print 的函数,它覆盖了内置方法 print。您应该重命名该函数。

标签: python python-3.x oop tkinter


【解决方案1】:

您的代码包含很多错误。我已经修复了它们。您需要使用<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)    

【讨论】:

  • 我想我在这里只传输部分代码时犯了一些错误。但是当你确定了这一点时,问题就解决了。非常感谢
猜你喜欢
  • 2018-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-16
  • 1970-01-01
  • 2017-08-24
  • 1970-01-01
  • 2018-05-21
相关资源
最近更新 更多