使用全局变量tkinter动态更改标签值
问题描述:
使用此代码我想根据全局变量LED 1和LED 2动态更改标签L3和L4,但无法使其与我的代码一起工作,任何人都可以对我有好的建议? 我知道它不会工作,因为方法init只是运行一次,我开始运行我的代码。 我在使用root.after之前阅读了一些建议,但我无法使用它处理我的代码。使用全局变量tkinter动态更改标签值
from Tkinter import *
import ttk
from ttk import *
suhu=30
cahaya=50
LED1='-'
LED2='-'
def mqttx():
def on_message(mqttc,obj,msg):
global LED1
global LED2
print "Telah Diterima message : "+msg.payload+" topik "+msg.topic
r.rpush(msg.topic,msg.payload)
datasuhu = r.lrange("suhu",-1,-1)
datacahaya = r.lrange("cahaya",-1,-1)
if msg.topic=="suhu":
if float(msg.payload)<=suhu :
mqttc.publish("2","1",qos=0,retain=False)
LED1="ON"
elif float(msg.payload)>suhu:
mqttc.publish("2","0",qos=0,retain=False)
LED1="OFF"
if msg.topic=="cahaya" :
if float(msg.payload) <=cahaya:
mqttc.publish("1","1",qos=0,retain=False)
LED2="ON"
elif float(msg.payload)>cahaya:
mqttc.publish("1","0",qos=0,retain=False)
LED2="OFF"
mqttc.on_message = on_message
mqttc.connect("localhost",1883)
mqttc.subscribe("suhu")
mqttc.subscribe("cahaya")
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("Subcriber")
self.style = Style()
self.style.theme_use("default")
self.pack(fill=BOTH, expand=1)
self.L3 =Label(self,text="LED 1 : "+LED1)
self.L3.pack
self.L3.grid()
self.L4 =Label(self,text="LED 2 : "+LED2)
self.L4.pack
self.L4.grid()
def main():
root = Tk()
root.geometry("250x150+300+300")
app = Example(root)
root.mainloop()
if __name__ == '__main__':
mqttx()
mqttc.loop_start()
main()
答
使用after()
来调用将改变标签中文本的函数。
我创建test()
功能来测试它没有功能mqttx()
from Tkinter import *
import ttk
from ttk import *
LED1 = '-'
LED2 = '-'
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
# run first time
self.update()
def initUI(self):
self.parent.title("Subcriber")
self.style = Style()
self.style.theme_use("default")
self.pack(fill=BOTH, expand=1)
self.L3 = Label(self,text="LED 1 : "+LED1)
self.L3.grid()
self.L4 = Label(self, text="LED 2 : "+LED2)
self.L4.grid()
def update(self):
#print('[DEBUG] update_text')
self.L3['text'] = "LED 1 : " + LED1
self.L4['text'] = "LED 2 : " + LED2
# run again after 500ms (0.5s)
self.after(500, self.update)
def test(root):
import random
global LED1
global LED2
print('[DEBUG] test')
LED1 = str(random.randint(1,10))
LED2 = str(random.randint(1,10))
# run again after 500ms (0.5s)
root.after(500, test, root)
def main():
root = Tk()
root.geometry("250x150+300+300")
app = Example(root)
test(root)
root.mainloop()
main()
+0
工作就像魅力!谢谢! –
这对于这个问题,太多的代码。请阅读[如何创建最小,完整和可验证的示例](http://*.com/help/mcve) –
使用'self.L3 ['text'] =“新文本”'来更改标签中的文本。 – furas
您可以使用'StringVar'作为LED1和LED2,然后将它们分别与L3和L4的'textvariable'关联。 – acw1668