您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python – 初学者 – GUI切换按钮

5b51 2022/1/14 8:20:32 python 字数 3548 阅读 468 来源 www.jb51.cc/python

我能请求一点帮助吗?我创建了一个带有切换按钮的GUI,用于切换LED,LED熄灭.我现在要做的是添加一些代码来更改按钮的文本,因为它在两个状态之间切换.我查了一些例子但是我不太清楚如何或者在哪里添加代码来使按钮文本切换.谢谢你的帮助.我的代码......# Idle 07_02_LED ON using GUI from time import sleep

概述

我能请求一点帮助吗?我创建了一个带有切换按钮的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()

总结

以上是编程之家为你收集整理的python – 初学者 – GUI切换按钮全部内容,希望文章能够帮你解决python – 初学者 – GUI切换按钮所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶