After two weeks of studying the Python.With the help of my teacher——tobias,I have learnt tentatively and wrote a programme which can communicate host with other devices.Mainly of GUI and mqtt areused in the programme.
import paho.mqtt.client as mqtt
import tkinter as tk
NUMBER_MESSAGES = 12
root = tk.Tk()
root.title("My Messenger")
root.geometry("800x500")
enter = tk.Entry()
enter.place(x=400,y=450)
client = mqtt.Client()
client.connect("192.168.1.200",1883,60)
text = []
def on_connect(client,userdata,flags,rc):
print("connect to the mqtt broker"+str(rc))
client.subscribe("python/course")
for i in range(NUMBER_MESSAGES):
text.append( tk.StringVar())
def on_message(client,userdata,msg):
if(msg.topic == "python/course"):
for i in range(NUMBER_MESSAGES-1):
text[i].set( text[i+1].get())
text[NUMBER_MESSAGES-1].set(str(msg.payload).strip('b').strip("'"))
client.on_connect = on_connect
client.on_message = on_message
def on_sending():
client.publish("python/course",enter.get())
#on_message.append(enter)
#tk.Label(root,textvariable = text,font = ("Arial",24)).pack()
for i in range(NUMBER_MESSAGES):
tk.Label(root,textvariable = text[i]).pack()
button = tk.Button(root, text = "send",command = on_sending)
button.place(x=500,y=450)
client.loop_start()
root.mainloop()
client.loop_stop()