我想读取标签变量的当前值,以便稍后将其发送到8x7段显示器。现在我打印它来检查值,我只返回0,而不是当前值
from Tkinter import *
class CounterAway(Frame):
def __init__(self, parent=None, **kw):
Frame.__init__(self, parent, kw)
self.countera = 0
self.ca = StringVar()
self._update_counter()
def _update_counter(self):
self.ca.set(str(self.countera))
def count_up(self):
self.countera += 1
if self.countera > 99 : self.countera = 0
self._update_counter()
def count_down(self):
self.countera -= 1
if self.countera < 0 : self.countera = 0
self._update_counter()
def main():
root = Tk()
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
"""root.geometry("%dx%d+0+0" % (w, h))"""
root.geometry('1000x1000')
counteraway = CounterAway(root)
Button(root, font=('Arial',30), width=10, text='Away +', command=counteraway.count_up).place(x=450, y=300)
Button(root, font=('Arial',30), width=10, text='Away -', command=counteraway.count_down).place(x=450, y=370)
Button(root, width=10, font=('Arial',30), text='Quit', command=root.destroy).place(x=10, y=10)
counteraway_label = Label(root, font="Arial 100 bold", fg="RED", textvariable=counteraway.ca).pack()
print counteraway.ca.get()
root.mainloop()
if __name__ == '__main__':
main()
我以为它可以与.get()一起使用,但这似乎是错误的
发布python代码时,请小心确保缩进是正确的
打印0的原因是因为这是执行
print counteraway.ca.get()
时变量的值。如果您在一个函数中打印了该值,该函数在通过按钮更新该值时再次调用,则该函数将正确打印例如,如果将
_update_counter
函数更改为:每次单击按钮更新值时,您都会看到它打印出正确的值
固定缩进后,完整代码如下所示:
在执行
main()
函数之前执行counteraway.ca.get()
,因此counteraway
变量尚未初始化。正因为如此,counteraway.ca.get()
不会起作用如果你把
以前
,它可能会起作用
相关问题 更多 >
编程相关推荐