python – 初学者 – GUI切换按钮

前端之家收集整理的这篇文章主要介绍了python – 初学者 – GUI切换按钮前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我能请求一点帮助吗?我创建了一个带有切换按钮的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()
原文链接:https://www.f2er.com/python/439684.html

猜你在找的Python相关文章