您好,登錄后才能下訂單哦!
這篇文章主要介紹了Python如何使用turtle和tkinter讓小海龜互動起來,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
請看下圖,turtle窗口圖標是一片小葉子,估計它就是繼承自 tkinter 庫。
參閱了一些資料,發現 turtle 方法可直接在 tkinter 的畫布Canvas上操作:
from tkinter import * from turtle import RawTurtle def circ(): tu.penup() tu.home() tu.clear() tu.speed(0) [x,y,R] = et1.get().split(',') try: x = int(x.replace('(','')) y = int(y.replace(')','')) R = int(R.strip()) except: x,y,R = 0,0,50 #輸入錯誤則賦予默認值 tu.goto(x,y-R) tu.pendown() tu.circle(R) def rect(): tu.penup() tu.home() tu.clear() tu.speed(0) tu.color('red', 'yellow') tu.begin_fill() [d,rad] = et2.get().split(',') try: d = int(d) rad = int(rad) except: d,rad = 200,216 #輸入錯誤則賦予默認值 tu.pendown() tu.back(d//5) while True: tu.forward(d) tu.left(rad) if abs(tu.pos()[0]+d//5)<0.1 and abs(tu.pos()[1])<0.1: break tu.end_fill() def taiji(): tu.penup() tu.home() tu.clear() tu.speed(0) d = et3.get() try: d = int(d) except: d = 120 #輸入錯誤則賦予默認值 tu.hideturtle() tu.goto(d//2,-d) tu.pendown() tu.begin_fill() tu.color('black','black') tu.circle(d,extent=180) tu.circle(d//2,extent=180) tu.circle(-d//2,extent=180) tu.end_fill() tu.circle(-d,extent=180) tu.penup() tu.goto(d//2,-d//6*4) tu.pendown() tu.begin_fill() tu.fillcolor("black") tu.circle(d//5,extent=360) tu.end_fill() tu.penup() tu.goto(d//2,d//3) tu.pendown() tu.begin_fill() tu.fillcolor("white") tu.circle(d//5,extent=360) tu.end_fill() tu.penup() def main(): global tu,et1,et2,et3 root = Tk() root.geometry('520x520+150+300') root.title('turtle在tkinter.Canvas上的操作') root.resizable(False, False) canvas = Canvas(root, width=640, height=400) canvas.pack() tu = RawTurtle(canvas) tu.hideturtle() et1 = Entry(root, width=12) et1.place(x = 30, y = 480) et1.insert(0,'(50,-20), 100') bt1 = Button(root,text=' 畫圓 ',command=circ) bt1.place(x = 60, y = 425) et2 = Entry(root, width=12) et2.place(x = 190, y = 480) et2.insert(0,'200, 216') bt2 = Button(root,text=' 多角星(或多邊形) ',command=rect) bt2.place(x = 180, y = 425) et3 = Entry(root, width=12) et3.place(x = 360, y = 480) et3.insert(0,'120') bt3 = Button(root,text=' 太極 ',command=taiji) bt3.place(x = 380, y = 425) root.mainloop() if __name__ == '__main__': main()
turtle和tkinter兩者搭配使用,使得 turtle 的畫圖參數可以由 tkinter 的控件當場設置,這樣就實現了turtle小海龜的現場互動,運行效果見圖二。
三個Entry控件,分別設置:
1. 圓心坐標和圓的直徑;
2. 多邊形的邊長和邊的轉動角度;
3. 太極圖的外圓直徑。
感謝你能夠認真閱讀完這篇文章,希望小編分享的“Python如何使用turtle和tkinter讓小海龜互動起來”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。