且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

GUI 按钮按住 - tkinter

更新时间:2023-09-29 17:07:34

按下按钮时设置标志,释放按钮时取消设置标志.不需要循环,因为您已经在运行循环 (mainloop)

Set a flag when the button is pressed, unset the flag when the button is released. There's no need for a loop since you're already running a loop (mainloop)

from Tkinter import * 
running = False
root = Tk()
def start_motor(event):
    global running
    running = True
    print("starting motor...")

def stop_motor(event):
    global running
    print("stopping motor...")
    running = False

button = Button(root, text ="forward")
button.pack(side=LEFT)
button.bind('<ButtonPress-1>',start_motor)
button.bind('<ButtonRelease-1>',stop_motor)
root.mainloop()

假设您确实想在按键被按下时做某事,您可以使用 after 设置一个动画循环.例如,要在按下按钮时每秒调用一次打印语句,您可以添加一个执行打印语句的函数,然后安排自己在一秒钟后调用.停止按钮只需要取消任何挂起的作业.

Assuming that you actually want to do something while the key is pressed, you can set up an animation loop using after. For example, to call a print statement once a second while the button is pressed you can add a function that does the print statement and then arranges for itself to be called one second later. The stop button merely needs to cancel any pending job.

这是一个例子.与原始代码的主要区别在于添加了 move 函数.我还添加了第二个按钮来展示如何使用相同的功能前进或后退.

Here's an example. The main difference to the original code is the addition of a move function. I also added a second button to show how the same function can be used to go forward or backward.

from Tkinter import * 
running = False
root = Tk()
jobid = None

def start_motor(direction):
    print("starting motor...(%s)" % direction)
    move(direction)

def stop_motor():
    global jobid
    root.after_cancel(jobid)
    print("stopping motor...")

def move(direction):
    global jobid
    print("Moving (%s)" % direction)
    jobid = root.after(1000, move, direction)

for direction in ("forward", "backward"):
    button = Button(root, text=direction)
    button.pack(side=LEFT)
    button.bind('<ButtonPress-1>', lambda event, direction=direction: start_motor(direction))
    button.bind('<ButtonRelease-1>', lambda event: stop_motor())

root.mainloop()