2016-12-14 142 views
0

我正在爲涉及向樹莓派顯示數據的學校開展此項目。我正在使用的代碼非常快速刷新(並需要刷新),但我需要一種讓用戶停止輸出的方式,我相信這需要某種關鍵事件。事情是,我是Python的新手,我無法弄清楚如何使用turtle.onkey()退出while循環。我發現這個代碼:如何在python中使用事件退出while循環?

import turtle 

def quit(): 
    global more 
    more = False 

turtle.onkey(quit, "Up") 
turtle.listen() 

more = True 
while more: 
    print("something") 

這是行不通的。我測試過了。我該如何做這項工作,或者有另一種方式來獲得用戶輸入而不中斷程序的流程?

回答

-4

你可以有你循環檢查文件是這樣的:

def check_for_value_in_file(): 
    with open('file.txt') as f: 
     value = f.read() 
    return value 

while check_for_value_in_file() == 'the right value': 
    do_stuff() 
+1

這並沒有回答這個問題... – Chris

+0

對不起,點擊提交一下,我就吸取了教訓。 – zemekeneng

+1

你的答案仍然與OP的問題無關。 – kay

0

有機會,你正試圖在一個交互式的IPython shell中運行代碼。這是行不通的。儘管如此,裸露的Python repl shell仍然有效。

在這裏,我找到了一個項目,試圖將烏龜帶到IPython:https://github.com/Andrewkind/Turtle-Ipython。我沒有對它進行測試,我也不確定這是否比簡單使用非糖殼更好。

1

而上線 檢查循環運行該代碼

import threading 

def something(): 
    while more: 
     print("something") 

th = threading.Thread(something) 
th.start() 
0

避免在Python烏龜圖形程序的無限循環:

more = True 
while more: 
    print("something") 

可以有效地阻止來自發射活動,包括一個旨在停止循環。相反,使用計時器事件來運行你的代碼,並允許其他事件火了:

from turtle import Screen 

more = True 

counter = 0 

def stop(): 
    global more 
    more = False 

def start(): 
    global more 
    more = True 
    screen.ontimer(do_something, 100) 

def do_something(): 
    global counter 
    print("something", counter) 
    counter += 1 

    if more: 
     screen.ontimer(do_something, 100) 

screen = Screen() 

screen.onkey(stop, "Up") 
screen.onkey(start, "Down") 
screen.listen() 

start() 

screen.mainloop() 

我添加了一個計數器,以你的程序只是讓你可以更容易地看到,當「東西」語句停止,我已經向下鍵添加重新啓動,以便您可以重新啓動它們。控制應始終達到mainloop()(或done()exitonclick()),以使所有事件處理程序有機會執行。一些無限循環允許事件觸發,但他們通常會調用烏龜方法,使其能夠控制一些時間,但仍然是錯誤的方法。