1
我正在設計一個簡單的Python程序,使用Turtle圖形模塊在屏幕上用箭頭鍵畫線。AttributeError:'_Screen'對象沒有屬性'mainloop'
import turtle
turtle.setup(400,500) # Determine the window size
wn = turtle.Screen() # Get a reference to the window
wn.title("Handling keypresses!") # Change the window title
wn.bgcolor("lightgreen") # Set the background color
tess = turtle.Turtle() # Create our favorite turtle
# The next four functions are our "event handlers".
def h1():
tess.forward(30)
def h2():
tess.left(45)
def h3():
tess.right(45)
def h4():
wn.bye() # Close down the turtle window
# These lines "wire up" keypresses to the handlers we've defined.
wn.onkey(h1, "Up")
wn.onkey(h2, "Left")
wn.onkey(h3, "Right")
wn.onkey(h4, "q")
# Now we need to tell the window to start listening for events,
# If any of the keys that we're monitoring is pressed, its
# handler will be called.
wn.listen()
wn.mainloop()
當我嘗試執行它時,返回以下錯誤。
Traceback (most recent call last):
File "C:\Users\Noah Huber-Feely\Desktop\PEN_Programming\Python\etchy_sketch1.py", line 32, in <module>
wn.mainloop()
AttributeError: '_Screen' object has no attribute 'mainloop'
我使用的是Python 2.7,並沒有遇到過Turtle圖形的麻煩。直到現在,我纔開始着手處理這個問題已經發生的關鍵輸入。
在網上搜索,我只找到有關不同問題和模塊的文章,而不是我目前遇到的文章。
讓我知道你是否需要更多信息。謝謝!
'wn.mainloop()'僅在Python 3中有效。在Python 2中,'mainloop'是'TK.mainloop'的一個(全局模塊)同義詞。在Python 3中,'mainloop'是'TurtleScreenBase'的一個方法,它調用'TK.mainloop'。當像這樣使用烏龜獨立時(即沒有嵌入到Tk中),只有一個屏幕,沒有辦法制造其他人。 – cdlane