[英]value not getting passed through button in tkinter
我对python语言非常陌生。我只是想在python程序上寻求帮助,在经过多次热烈尝试之后,我设法以某种方式编写了该程序。
from time import sleep
from Tkinter import *
def qf(par):
print(par)
class App:
def __init_(self, master):
frame = Frame(self, master)
frame.pack()
self.button = Button(frame, text='LED ON', command=self.convert0)
self.button.grid(row=5, coloumnspan=5)
def convert0(self, tog[0]):
tog[0] = not tog[0]
if tog[0]:
self.button.config(text='LED OFF')
else:
self.button.config(text='LED OFF'. command=lambda:qf("1!!!"))
root = Tk()
root.wm_title('LED Prog')
app = App(root)
root.mainloop()
程序的输出是当我单击“ LED ON”按钮时,它传递值“ 1 !!!”。 并且按钮卡在“ LED ON”上,而不变为“ LED OFF”。
我想要的是那个时候按钮“ LED ON”时1 !!!! 应在输出中显示,并且当按钮为“ LED OFF”时,将不显示任何值。
我知道这对于python专家来说可能是一个小的代码更改,但是在这里几乎不需要帮助。 任何人都可以分享一些学习python的链接。
提前致谢。 请不要阻止我正在使用python 2.7.9的问题
使用button.configure(text=)
更改文本,在OFF
和ON
之间交替使用变量保存状态。
from time import sleep
from Tkinter import *
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.button = Button(frame, text='LED ON', command=self.convert0)
self.button.pack()
self.state = 1
def convert0(self):
states = ['ON', 'OFF']
self.state = not self.state
# True == 1 and False == 0
self.button.configure(text='LED {0}'.format(states[not self.state]))
root = Tk()
root.wm_title('LED Prog')
app = App(root)
root.mainloop()
使用grid
法:
grid(row=, column=) then you can give `rowspan` or `columnspan`.
如果我很了解您,这就是您想要的:
from Tkinter import *
class App:
def __init__(self, master):
""" The constructor consists of a a root widget to which
is attached one Button child widget.
"""
frame = Frame(master)
frame.pack()
self.led = Button(frame, fg="red", text="Start", width=15,command=self.button_state)
self.led.pack() # Use pack() if no other widgets are planned to take place
def button_state(self):
""" Switch the button text from LED OFF to LED ON: 1
At the start of the program, the button text is set to 'Start'.
"""
if self.led["text"] == "LED OFF" or self.led["text"] == "Start":
self.led["text"] ="LED ON: 1"
else:
self.led["text"]="LED OFF"
root = Tk()
root.wm_title('LED Prog')
app = App(root)
root.mainloop()
结果:
单击按钮将在这两种状态之间切换:
终于得到了我一直在寻找的希望,希望对其他人也有所帮助。
from time import sleep
from Tkinter import *
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.button = Button(frame, text='LED ON', command=self.convert0)
self.button.grid(row=2, column=0)
self.LED = Label(frame).grid(row=2, column=1)
def convert0(self, tog=[0]):
tog[0] = not tog[0]
if tog[0]:
print('1')
self.button.config(text='LED OFF')
else:
self.button.config(text='LED ON')
root = Tk()
root.wm_title('LED on & off program')
app = App(root)
root.mainloop()
这完全可以按我的意愿工作。
@WoLy感谢您的努力,但我一直在寻找这个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.