使用此代码,我想根据全局可变LED 1和LED 2使标签L3和L4动态变化,但是不能使其与下面的代码一起使用,有人对我有好的建议吗?我知道它将无法正常工作,因为方法init每次运行我的代码时都会运行一次。在使用root.after之前,我阅读了一些建议,但无法使其与我的代码一起使用。
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()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句