加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 初学者 – GUI切换按钮

发布时间:2020-12-16 21:43:18 所属栏目:Python 来源:网络整理
导读:我能请求一点帮助吗?我创建了一个带有切换按钮的GUI,用于切换LED,LED熄灭. 我现在要做的是添加一些代码来更改按钮的文本,因为它在两个状态之间切换. 我查了一些例子但是我不太清楚如何或者在哪里添加代码来使按钮文本切换. 谢谢你的帮助. 我的代码 # Idle 0

我能请求一点帮助吗?我创建了一个带有切换按钮的GUI,用于切换LED,LED熄灭.

我现在要做的是添加一些代码来更改按钮的文本,因为它在两个状态之间切换.

我查了一些例子但是我不太清楚如何或者在哪里添加代码来使按钮文本切换.

谢谢你的帮助.

我的代码……

# Idle 07_02_LED ON using GUI
from time import sleep

from Tkinter import *

class App:

    def __init__(self,master): 
        frame = Frame(master)
        frame.pack()
        Label(frame,text='Turn LED ON').grid(row=0,column=0)

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

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


    def convert0(self,tog=[0]):

        tog[0] = not tog[0]
        if tog[0]:
        print('LED 0 OFF')

        else:
        print('LED 0 ON')

root = Tk()

root.wm_title('LED on & off program')

app = App(root)

root.mainloop()
最佳答案
你需要做两件事:

>将按钮定义为self.button,使其成为App的实例属性.这样,您可以通过self在convert0中访问它.
>使用Tkinter.Button.config更新按钮的文本.

下面是该脚本的固定版本.我在评论框中添加了我更改的内容:

# Idle 07_02_LED ON using GUI
from time import sleep

from Tkinter import *

class App:

    def __init__(self,column=0)

        ####################################################################
        self.button = Button(frame,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()

root.wm_title('LED on & off program')

app = App(root)

root.mainloop()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读