这段代码是在 tk 窗口上接收和显示文本。但我在这里要实现的是:当字符从主机发送到从机时。接收slave上的字符,在dict中查找字符,显示key对应的值。我试过但没有成功,任何人都可以帮助我提供正确的代码。
例如:当slave收到一个叫'hw'的键时,它必须显示“hello world”,当收到'0'时,应该显示“你好吗?” 在 tk 文本小部件窗口上。提前致谢。
import serial
import threading
import Queue
import Tkinter as tk
from Tkinter import *
import time
import sys
class SerialThread(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
s = serial.Serial('COM11',9600)
while True:
if s.inWaiting():
text = s.readline(s.inWaiting())
self.queue.put(text)
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.geometry("1360x750")
self.time = ''
self.clock = tk.Label(self, font=('times', 50, 'bold'), fg='black', bg='yellow')
self.clock.pack(side='bottom', anchor='se')
frameLabel = tk.Frame(self, padx=10, pady =50)
self.text = tk.Text(frameLabel, wrap='word', bg=self.cget('bg'), relief='flat')
frameLabel.pack()
self.text.pack()
self.queue = Queue.Queue()
thread = SerialThread(self.queue)
thread.start()
self.process_serial()
self.msgs = {
'hw':"hello world",
'wpp':"welcome to python programming",
'h':"hello",
0:"how are you?",
1:"bye....",
'egm': "english general message how are you",
'egm2':"If the world is flat be carefull not to fall off"
}
def process_serial(self):
self.time = time.strftime('%H:%M:%S')
self.clock.config(text=self.time)
firstitem = True
while self.queue.qsize():
try:
new = self.queue.get()
size = sys.getsizeof(new)
if size<40:
self.text.config(font='TimesNewRoman 100')
elif size>=40 and size<70:
self.text.config(font='TimesNewRoman 75')
else:
self.text.config(font='TimesNewRoman 50')
if firstitem:
self.text.delete(1.0, 'end')
firstitem = False
self.text.tag_configure("tag-center", justify='center')
#self.text.tag_add("center", 1.0, "end")
self.text.insert('end', my_dictionary.setdefault(signal, 'wrong signal'))
#self.text.insert('end', new, 'tag-center')
except Queue.Empty:
pass
self.after(1000, self.process_serial)
app = App()
app.mainloop()