【问题标题】:Python 3 Tkinter - Disabling buttons out of order codePython 3 Tkinter - 禁用按钮乱序代码
【发布时间】:2013-12-10 02:57:04
【问题描述】:

目前,当满足特定条件时,我正在尝试禁用 UI 中的某些按钮。唯一的问题是我只能在按钮创建后更改它的状态。

我创建了一个Disabler 类来为我处理这个问题,但事实证明让它运行起来很困难。如果我让它工作,禁用器的任务是禁用与我的计时器类有关的所有按钮,以便用户知道它们不可点击(或者它们不做任何事情)。

以下是我的代码的缩减版,仅显示按钮。

from tkinter import *

root = Tk()

class StopWatch(Frame):
    def __init__(self, parent=None, **kw):
        Frame.__init__(self, parent, kw)
        StopWatch.on = 1
        TimeAdjustLabel = LabelFrame(root, text='Frame',)
        TimeAdjustLabel.grid(column=0, row=1, padx=10, pady=10)
        StopWatch.b1 = Button(TimeAdjustLabel, text='Reset', width=10, command=self.Start)
        StopWatch.b1.grid(row=0, column=0)

    def Start(self, event=None):
        if StopWatch.on == 0:
            StopWatch.on = 1
        else: 
            StopWatch.on = 0
        self.enable()

    def enable(self):
        if StopWatch.on == 0:
            StopWatch.b1.configure(state=DISABLED)
        else: 
            StopWatch.b1.configure(state=NORMAL)


def main():
    sw = StopWatch(root)
    root.mainloop()

if __name__ == '__main__':
    main()

【问题讨论】:

  • 你为什么要创建一个禁用类?只要一个方法就足够了......你不觉得吗?
  • 确实会有。我将如何使它工作呢?可以直接从 Stopwatch 类运行方法吗?
  • 将按钮和标签框放在秒表类中,然后使用self
  • 我更新了上面的问题,我走对了吗?如何让self.enable() 查找下面的def 而不是Stopwatch

标签: python button python-3.x tkinter


【解决方案1】:

你快到了。你看到它的那一刻就会明白。我想告诉你的是:

from tkinter import *
root = Tk()

class StopWatch(Frame):
    def __init__(self, parent=None, **kw):
        Frame.__init__(self, parent, kw)
        self.on = 1
        TimeAdjustLabel = LabelFrame(root, text='Frame',)
        TimeAdjustLabel.grid(column=0, row=1, padx=10, pady=10)
        self.b1 = Button(TimeAdjustLabel, text='Reset', width=10, command=lambda:self.Start(self.on))
        self.b1.grid(row=0, column=0)

    def Start(self, onoff):
        if onoff == 0:
            onoff = 1
        else: 
            onoff = 0
        self.enable(onoff)


    def enable(self,enableonoff):
        if enableonoff == 0:
            self.b1.configure(state='disabled')
        else: 
            self.b1.configure(state='normal')

def main():
    app = StopWatch(root)
    root.mainloop()

if __name__ == '__main__':
    main()

【讨论】:

  • 啊,当然。感谢那。我有一些小问题,但我应该能够自己解决剩下的问题。
猜你喜欢
  • 2018-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多