【发布时间】:2021-02-26 11:04:08
【问题描述】:
我正在尝试制作用于从 arduino 获取数据的 GUI。我想在按下按钮后输入文件名并开始数据采集。在我按下按钮的那一刻,什么都没有发生,但是当我关闭窗口时它开始了。我希望窗户保持打开状态。
我的代码如下:
import serial
from tkinter import *
import csv
def start_measurement():
global file_name
file_name = entry_1.get()
my_window = Tk()
label_1 = Label(my_window, text = "File name: ")
entry_1 = Entry(my_window)
button_1 = Button(my_window, text = "Save", command = start_measurement)
label_1.grid(row=0, column=0)
entry_1.grid(row=0, column=1)
button_1.grid(row=0, column=2)
my_window.mainloop()
arduinoData =serial.Serial('COM15', 9600)
while (True):
while(arduinoData.inWaiting()==0):
pass
arduinoString = arduinoData.readline().decode().split(',')
x=float(arduinoString[0])
y=float(arduinoString[1])
print(x, y)
with open(file_name + '.csv', 'a', newline='') as f:
writer = csv.writer(f, delimiter = ',')
writer.writerow([x, y])
f.close()
【问题讨论】:
-
删除
my_window.mainloop()和内部while True说my_window.update()。虽然最好在单独的线程中移动函数内部的逻辑,否则while循环会阻塞mainloop()