【问题标题】:How to check for a button press while another tk.button function runs?如何在另一个 tk.button 功能运行时检查按钮是否按下?
【发布时间】:2019-08-28 14:50:02
【问题描述】:

我目前正在为我的实验室中的倾斜表创建一个带有 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()

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

【问题讨论】:

  • 你必须使用线程
  • @BlackThunder Thread(target=?) 我的目标是 Pause 还是 pauseButton?
  • 我不使用线程,所以你必须自己弄清楚
  • 线程不是唯一的答案,但如果 GUI 要保持响应,您必须实际上从按钮命令返回相当快。任何正在进行的活动都可以在一个线程中执行,或者在您稍后通过.after() 安排的函数中一次完成一小部分(如果活动仍未完成,它可以使用.after() 重新安排自己)。
  • 您可能只使用win.after(0, Up) 而不是直接调用Up()

标签: python tkinter


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-05
    • 2022-07-16
    • 2020-01-02
    • 1970-01-01
    相关资源
    最近更新 更多