Python 3.x 使用Tkinter在GUI中进行while循环
我是特金特领域的初学者。我有一个小任务要用Tkinter创建GUI。我只需要几个按钮,如Python 3.x 使用Tkinter在GUI中进行while循环,python-3.x,user-interface,tkinter,Python 3.x,User Interface,Tkinter,我是特金特领域的初学者。我有一个小任务要用Tkinter创建GUI。我只需要几个按钮,如读取数据和停止读取数据和退出。这里的数据来自串行端口 我已经创建了代码。我的想法是,当我点击readdata按钮时,它应该转到while循环,在那里它必须读取数据并在GUI上打印它们。 当我单击“停止读取数据”时,它应该停止读取数据 然而,当我点击readdata按钮时,当循环和GUI挂在那里时,它将被激活。我无法点击任何按钮,也看不到数据 这是我的密码: import tkinter as tk impor
读取数据
和停止读取数据
和退出
。这里的数据来自串行端口
我已经创建了代码。我的想法是,当我点击readdata
按钮时,它应该转到while循环,在那里它必须读取数据并在GUI上打印它们。
当我单击“停止读取数据”时,它应该停止读取数据
然而,当我点击readdata
按钮时,当循环和GUI挂在那里时,它将被激活。我无法点击任何按钮,也看不到数据
这是我的密码:
import tkinter as tk
import serial,time
import datetime
import array as arr
addr = "COM10" ## serial port to read data from
baud = 115200 ## baud rate for instrument
ser = serial.Serial(
port = addr,\
baudrate = baud,\
parity=serial.PARITY_NONE,\
stopbits=serial.STOPBITS_ONE,\
bytesize=serial.EIGHTBITS,\
timeout=1)
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.appName = tk.Button(self,fg="red", bg="blue")
self.appName["text"] = "SCAN "
self.appName.pack(side="top")
self.startScanBtn = tk.Button(self,fg="red", bg="green")
self.startScanBtn["text"] = "Start Scanning "
self.startScanBtn["command"] = self.scan
self.startScanBtn.pack(side="left")
self.stopScanBtn = tk.Button(self,fg="black", bg="red")
self.stopScanBtn["text"] = "Stop Scanning "
self.stopScanBtn.pack(side="right")
self.quit = tk.Button(self, text="QUIT", fg="red",
command=self.master.destroy)
self.quit.pack(side="bottom")
def scan(self):
while(true):
c = ser.readline() # attempt to read a character from Serial
line = c.decode('utf-8').replace('\r\n', '')
tk.Label(self,text = line).pack()
root = tk.Tk()
app = Application(master=root)
app.mainloop()
GUI变得无响应的原因是python在while循环中很忙。您可能想考虑使用多线程在不同的线程中使用扫描功能,线程。线程将是一个很好的开始位置。然后您需要将数据从扫描线程发送到主线程以在GUI中显示,PySubub可以提供帮助。希望这有帮助