gpt4 book ai didi

python - 初学者 - GUI 切换按钮

转载 作者:太空狗 更新时间:2023-10-30 01:15:32 25 4
gpt4 key购买 nike

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

最佳答案

你需要做两件事:

  1. 将按钮定义为self.button,使其成为App的实例属性。这样,您就可以通过 selfconvert0 中访问它。

  2. 使用 Tkinter.Button.config更新按钮的文本。

以下是脚本的固定版本。我将更改的内容放在评论框中:

# 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)

####################################################################
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()

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

app = App(root)

root.mainloop()

关于python - 初学者 - GUI 切换按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20547544/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com