【问题标题】:Toggle LED Python 3.x tkinter切换 LED Python 3.x tkinter
【发布时间】:2023-03-11 10:51:01
【问题描述】:

我正在尝试使用 GUI 来打开和关闭 LED。

当我执行代码时,我得到一个空白框,标题为“tk”。

import tkinter as tk

class Application(tk.Frame):
    def __init__(self, master=None): 
        super().__init__(master)
        self.pack()
        Label(frame, text='Turn LED ON').grid(row=0, column=0)
        Label(frame, text='Turn LED OFF').grid(row=1, column=0)

        self.button = Button(frame, text='LED 0 ON', command=self.convert0)
        self.button.grid(row=2, columnspan=2)

    def convert0(self, tog=[0]):
        tog[0] = not tog[0]
        if tog[0]:
            self.button.config(text='LED 0 OFF')
        else:
            self.button.config(text='LED 0 ON')

root = tk.Tk()
app = Application(master=root)
app.mainloop()

【问题讨论】:

    标签: python-3.x tkinter raspberry-pi3 gpio led


    【解决方案1】:

    您的代码需要多次修复。

    首先,按原样运行它给了我以下错误:

    NameError: name 'Label' is not defined
    

    当然,事实并非如此。 定义的是tk.Label,所以我们把这两行改一下:

    Label(frame, text='Turn LED ON').grid(row=0, column=0)
    Label(frame, text='Turn LED OFF').grid(row=1, column=0)
    

    进入:

    tk.Label(frame, text='Turn LED ON').grid(row=0, column=0)
    tk.Label(frame, text='Turn LED OFF').grid(row=1, column=0)
    

    现在,我提出了以下错误:

    NameError: name 'frame' is not defined
    

    果然,也不是。 您可能指的是Application 类扩展了tk.Frame 类的事实。 嗯,这是真的,但这并不能告诉我们frame 是什么。 我假设frame 的意思是“实例,但被视为Frame 实例”。 在这种情况下,self 就足够了(这实际上是需要的)。 所以我们开始吧,以下三行:

    tk.Label(frame, text='Turn LED ON').grid(row=0, column=0)
    tk.Label(frame, text='Turn LED OFF').grid(row=1, column=0)
    
    self.button = Button(frame, text='LED 0 ON', command=self.convert0)    
    

    变成:

    tk.Label(self, text='Turn LED ON').grid(row=0, column=0)
    tk.Label(self, text='Turn LED OFF').grid(row=1, column=0)
    
    self.button = Button(self, text='LED 0 ON', command=self.convert0) 
    

    现在,有人告诉我

    NameError: name 'Button' is not defined
    

    我相信你已经开始明白这一点了。 所以让我们用tk.Button替换Button

    self.button = tk.Button(self, text='LED 0 ON', command=self.convert0)
    

    到这里,窗口就会显示出来,有两个标签和一个漂亮的按钮,点击时文本会发生变化。

    【讨论】:

    • 感谢您的逐步修复!
    猜你喜欢
    • 1970-01-01
    • 2018-08-25
    • 1970-01-01
    • 2012-10-17
    • 1970-01-01
    • 1970-01-01
    • 2012-03-20
    • 2015-01-09
    • 1970-01-01
    相关资源
    最近更新 更多