如何在另一个 tk.button 函数运行时检查按钮是否按下?



我目前正在实验室中为倾斜台创建一个带有tkinter的GUI。我有上下按钮编程为打开一个引脚,直到桌子达到一定角度,通过 Arduino 从测斜仪读取,然后关闭引脚。所以目前与每个按钮关联的功能会反复读取角度,直到达到正确的角度,但我也希望能够在我选择时关闭引脚。问题是,当与Up关联的函数正在运行时,程序不会检查任何按钮按下。如何获得暂停按钮来中断该功能?

我尝试使用线程库实现中断,但似乎 tkinter 不会在与 button(( 关联的函数运行时运行任何其他代码。

import tkinter as tk
from tkinter import *
import RPi.GPIO as GPIO
import time
import serial
global read_serial
win = Tk()
def Up():
if read_serial < target: 
global read_serial  #read_serial is edited elsewhere not included here
GPIO.output(40,GPIO.HIGH)
time.sleep(.05)
read_serial=ser.readline().rstrtip().decode("utf-8")
read_serial=float(read_serial)
Up()
else:
GPIO.otuput(40,GPIO.LOW)
def Pause():
GPIO.output(40,GPIO.LOW)
upButton = Button(win,text='UP',command=Up)
pauseButton = Button(win,text='PAUSE',command=Pause)
upButton.grid(row=1)
pauseButton.grid(row=2)
win.mainloop()

我不想粘贴太多代码,但是如果我缺少任何关键部分,我可以包含更多代码。我想在按暂停时中断 Up((,但是一旦我按 Up,程序就会忽略任何输入,直到read_serial大于目标。是否可以实现中断以使用 tkinter 检查其他按钮按下?

使用tkinter 时,在后台运行函数的最简单方法是使用.after((方法,这允许您不需要线程模块。.after(( 中的 0 是等待它执行给定函数的毫秒数。

示例(不是最好的方法,因为它现在有另一个功能(:

def bnt_up():
win.after(0, Up)
upButton = Button(win,text='UP',command=bnt_up)

最新更新