Python Tkinter仅适用于一次按钮按下,而不适用于其他按钮按下?
我使用Tkinter窗口通过串行端口将信息传递给arduino,arduino将步进电机转动一定的步数。基本上,我有按钮,对应的步骤,我希望电机采取的数量。当我按下按钮时,我想让马达移动那么多步。我会发布一些我的代码片段,但基本上我的问题是,第一次按下按钮时窗口工作得很好,但当我点击其他按钮让电机继续运转时,我什么也看不到。Tkinter窗口似乎只适用于一次单击,或者卡在回调函数或其他什么东西中 回调函数:Python Tkinter仅适用于一次按钮按下,而不适用于其他按钮按下?,python,tkinter,serial-port,arduino,Python,Tkinter,Serial Port,Arduino,我使用Tkinter窗口通过串行端口将信息传递给arduino,arduino将步进电机转动一定的步数。基本上,我有按钮,对应的步骤,我希望电机采取的数量。当我按下按钮时,我想让马达移动那么多步。我会发布一些我的代码片段,但基本上我的问题是,第一次按下按钮时窗口工作得很好,但当我点击其他按钮让电机继续运转时,我什么也看不到。Tkinter窗口似乎只适用于一次单击,或者卡在回调函数或其他什么东西中 回调函数: def firstGrating(): arduino.write('1800'
def firstGrating():
arduino.write('1800')
tkMessageBox.showwarning(title= 'Spectrometer', message = 'I am moving to the 1800 Grating...')
tkMessageBox.showwarning(title= 'Spectrometer', message = 'Please Wait Until I Tell You That I AM FINISHED!!!')
while True:
message = arduino.readline()
if len(message) > 10:
tkMessageBox.showwarning(title= 'Spectrometer', message = message)
return
def secondGrating():
arduino.write('150')
tkMessageBox.showwarning(title= 'Spectrometer', message = 'I am moving to the 150 Grating...')
tkMessageBox.showwarning(title= 'Spectrometer', message = 'Please Wait Until I Tell You That I AM FINISHED!!!')
while True:
message = arduino.readline()
if len(message) > 10:
tkMessageBox.showwarning(title= 'Spectrometer', message = message)
return
def thirdGrating():
arduino.write('3600')
tkMessageBox.showwarning(title= 'Spectrometer', message = 'I am moving to the 3600 Grating...')
tkMessageBox.showwarning(title= 'Spectrometer', message = 'Please Wait Until I Tell You That I AM FINISHED!!!')
while True:
message = arduino.readline()
if len(message) > 10:
tkMessageBox.showwarning(title= 'Spectrometer', message = message)
return
这是我尝试设置Tkinter窗口的部分:
win = Tk()
win.geometry("600x400+500+500")
win.title('Spectrometer Controller')
mlabel = Label(text = 'Select One of The Available Gratings')
mlabel.pack()
mButton1 = Button(win, text = '1800', command = lambda: firstGrating())
mButton1.pack()#.grid(row=0, column=1)
mButton2 = Button(win, text = '150', command = lambda: secondGrating())
mButton2.pack()#.grid(row=0, column=2)
mButton3 = Button(win, text = '3600', command = lambda: thirdGrating())
mButton3.pack()#.grid(row=0, column=3)
win.mainloop()
你说得对,电话卡在回拨电话里了
Tkinter
的mainloop()
与while
循环产生冲突并变得无响应,因此在while
循环运行时无法按下另一个按钮
您可以查看创建编程循环的方法,该循环将保持GUI的响应性。下面是一个例子:
def callback(flag):
global loop
if flag is True:
print('message')
... other logic ...
# start the after method to call the callback every 100ms
loop = root.after(100, callback, True)
else:
# cancel the after method if the flag is False
root.after_cancel(loop)
root = Tk()
# use a lambda expression to pass arg to callback in button commands
Button(root, text='start', command=lambda: callback(True)).pack()
Button(root, text='stop', command=lambda: callback(False)).pack()
mainloop()
您还可以将GUI和业务保持在单独的线程中,但这通常是需要设置的PITA。after()
方法通常同样有效