多线程Python Tkinter串行监视器中的按钮问题



我尝试创建一个串行监视器,可以发送和接收来自串行端口的消息与Tkinter作为GUI。我做了两个线程,因为当程序搜索新数据时没有冻结GUI。


Tkinter GUI很简单:

  • 1输入要发送的文本
  • 1标签用于显示收到的消息
  • 1键发送条目消息

我的问题是当我运行程序时,我点击按钮,什么也没发生。我认为按钮不再加载时,我开始我的两个线程。如何解决这个问题?

import threading
from tkinter import *
import tkinter as tk
import serial
root = tk.Tk()
COM = "COM3"
ser = serial.Serial(port=COM, baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, timeout=2)
ser.isOpen()
msg = ""

# read Serial
def ReadSerial():
global msg
msg = ""
msg = ser.readline()[:-2].decode("utf-8")
if msg != "":
print(msg)

return msg
# write Serial
def WriteSerial(sendmsg):
print("send")
ser.write(bytes(sendmsg, 'utf-8'))
ReadSerial()

# Tkinter
root.title("WIP NAME")
root.geometry("650x400")
inputData = Entry(root, text="<Slave1&p>") # input for enter the message to write
entrymsg = inputData.get() # get the massage
buttonMsg = Button(root, text="send", command = WriteSerial(entrymsg)) # create a send button for send the message
readData = Label(root, text=msg) # show message in Tkinter
ReadSerial()
# show items
inputData.grid()
readData.grid()
buttonMsg.grid()

# GUI thread
def TkinterGui():
while 1==1:
global msg
entrymsg = inputData.get()

# Serial thread
def SerialProgram():
while 1==1:
ReadSerial()
readData.update_idletasks()

x = threading.Thread(target=TkinterGui, args=())
y = threading.Thread(target=SerialProgram, args=())
x.start()
y.start()
root.mainloop()

真的很感谢你@acw1668,我已经为这个项目工作了一个星期了。正确的命令是:

buttonMsg = Button(root, text="send", command = lambda: WriteSerial(inputData.get()))

和整个代码:

import threading
from tkinter import *
import tkinter as tk
import serial
root = tk.Tk()
COM = "COM3"
ser = serial.Serial(port=COM, baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, timeout=2)
ser.isOpen()
msg = ""

# read Serial
def ReadSerial():
global msg
msg = ""
msg = ser.readline()[:-2].decode("utf-8")
if msg != "":
print(msg)

return msg
# write Serial
def WriteSerial(sendmsg):
print("send")
ser.write(bytes(sendmsg, 'utf-8'))
ReadSerial()

# Tkinter
root.title("WIP NAME")
root.geometry("650x400")
inputData = Entry(root, text="<Slave1&p>") # input for enter the message to write
entrymsg = inputData.get() # get the massage
buttonMsg = Button(root, text="send", command = lambda: WriteSerial(inputData.get())) # create a send button for send the message
readData = Label(root, text=msg) # show message in Tkinter
ReadSerial()
# show items
inputData.grid()
readData.grid()
buttonMsg.grid()

# GUI thread
def TkinterGui():
while 1==1:
global msg
entrymsg = inputData.get()

# Serial thread
def SerialProgram():
while 1==1:
ReadSerial()
readData.update_idletasks()

x = threading.Thread(target=TkinterGui, args=())
y = threading.Thread(target=SerialProgram, args=())
x.start()
y.start()
root.mainloop()

注:对不起,如果我的英语不是很好理解,我是法国人:)

最新更新