【问题标题】:Problem with using keyboard module and turtle together一起使用键盘模块和乌龟的问题
【发布时间】:2019-05-30 07:22:47
【问题描述】:

我正在编写一个脚本来读取我的击键并在海龟中绘制简单的形状。 为了记录击键,我使用keyboard 模块,我使用turtle 进行绘图。

由于在 keyboard 模块中使用了线程,我感到很震惊。

我目前正在做的是-

  1. 我使用keyboard.add_hotkey 方法添加了热键。
  2. 如果我按下某个键,该字母会被添加到列表中(名为 data)以供以后使用。
  3. 当我按下 Ctrl+Shift+S 的组合时,会调用保存函数。在 save 函数中,实例化了一个海龟窗口,列表data 一次弹出一个字母。形状是根据弹出的字母绘制的。
  4. 当列表为空时,我保存绘图并关闭海龟窗口。

我面临的问题是,一旦调用了 save 函数,程序就会停止监听其他调用。这可能是由于在keyboard 模块中使用了线程。

代码附在这里-

def start():
    #turtle.mainloop()
    s=turtle.Screen().setup( width = WIDTH, height = HEIGHT, startx = 0, starty = 0)
    global t
    t=turtle.Turtle()
    turtle.ht()
    t.ht()

def save():

    start()
    global t
    global data
    t.speed(0)

    while data:
        fun = data.pop()

        if fun=='c':
            draw_circle()
        elif fun=='r':
            draw_rectangle()
        elif fun=='p':
            draw_polygon()
        elif fun=='h':
            draw_hexagon()
        elif fun=='t':
            draw_triangle()
        elif fun=='m':
            draw_pentagon()

    ts = turtle.getscreen()
    ts.getcanvas().postscript(file="drawing.eps")
    img = Image.open('drawing.eps')
    img.save('drawing.png')
    turtle.bye()

def push_fun(fun):
    data.append(fun)

if __name__=='__main__':
    keyboard.add_hotkey('ctrl+shift+s', save)
    keyboard.add_hotkey('ctrl+shift+e', exit)
    keyboard.add_hotkey('ctrl+shift+p', send_to_server)
    # keyboard.add_hotkey('ctrl+shift+s', save, args=(data))
    keyboard.add_hotkey('c', push_fun, args=('c',))
    keyboard.add_hotkey('s', push_fun, args=('t',))
    keyboard.add_hotkey('h', push_fun, args=('h',))
    keyboard.add_hotkey('p', push_fun, args=('p',))
    keyboard.add_hotkey('r', push_fun, args=('r',))
    keyboard.wait()

调用save函数后,程序停留在keyboard.wait()部分,但不监听任何其他按键。

【问题讨论】:

    标签: python python-3.x multithreading turtle-graphics


    【解决方案1】:

    你可以通过设置一个按键来结束等待:

    keyboard.wait('space')
    

    但是没有给定任何键的keyboard.wait()会永远阻止所有击键

    我不确定你为什么把它放在那里,我什至不确定它为什么会捡起任何东西,但我认为你可以这样做:

    if __name__=='__main__':
        '''your keystrokes'''
        while True: #or set a timer or something
            pass
    

    你没有给我完整的代码,所以我不能确定它是否有效

    还需要在 push_fun 函数中全局化列表数据

    希望对你有帮助:)

    【讨论】:

    • while 循环中的pass 会导致它只运行一次,不是吗?
    • @PrashantSengar pass 只是一个占位符,当循环或 def 等中没有代码时,您正在考虑 break :)
    • 代码还是有同样的问题。如果你能帮助我,这里是full code
    猜你喜欢
    • 2017-08-09
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2021-06-18
    • 2021-06-25
    • 2021-12-17
    • 2020-05-11
    相关资源
    最近更新 更多