【发布时间】:2020-05-31 00:41:09
【问题描述】:
我正在尝试使用方向按钮制作一个简单的工具路径程序。它可以工作,但有时释放按钮是无效的,乌龟停止点击“主页”按钮。否则它就像我没有释放按钮一样持续运行。
代码如下:
from tkinter import *
from turtle import RawTurtle, TurtleScreen
def showPos():
monitor.delete('1.0', END)
monitor.insert(END, "X: " + str(tool.ycor()) +" Z: " + str(tool.xcor()))
def goHome():
tool.home()
showPos()
stop_move()
def goUp():
tool.sety(tool.ycor() + 10)
def goDown():
tool.sety(tool.ycor() - 10)
def goRight():
tool.setx(tool.xcor() + 10)
def goLeft():
tool.setx(tool.xcor() - 10)
def stop_move():
global jobid
root.after_cancel(jobid)
def move(direction):
global jobid
if direction == "-X":
goDown()
if direction == "+X":
goUp()
if direction == "-Z":
goLeft()
if direction == "+Z":
goRight()
jobid = root.after(10, move, direction)
showPos()
jobid = None
root = Tk()
root.title("CNC Lathe")
canvas = Canvas(root, width=800, height=600)
canvas.pack()
screen = TurtleScreen(canvas)
screen.bgcolor("black")
screen.register_shape("wnmg.gif")
tool = RawTurtle(screen, shape="wnmg.gif")
tool.pencolor("white")
monitor = Text(root, height=1, width=16, font="Helvetica")
monitor.pack()
topFrame = Frame(root)
topFrame.pack()
middleFrame = Frame(root)
middleFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack()
for direction in ("-X", "+X", "-Z", "+Z"):
if direction == "+X":
button = Button(topFrame, text=direction)
button.pack()
if direction == "-X":
button = Button(bottomFrame, text=direction)
button.pack()
if direction == "-Z":
button = Button(middleFrame, text=direction)
button.pack(side=LEFT)
if direction == "+Z":
button = Button(middleFrame, text=direction)
button.pack(side=RIGHT)
button.bind('<ButtonPress-1>', lambda event, direction=direction: move(direction))
button.bind('<ButtonRelease-1>', lambda event: stop_move())
Button(middleFrame, text="Home", command=goHome).pack()
root.mainloop()
我尝试在“root.after_cancel()”方法之后将变量“jobid”设置为“None”,但没有任何改变。有时这似乎没有检测到按钮的释放。有谁知道解决办法吗?
【问题讨论】:
-
“似乎没有检测到按钮的释放”:可以,但是您需要一个条件来停止进一步调用
root.after(10, move, direction).
标签: python python-3.x events button tkinter