WHCSRL 技术网

Python 允许小海龟交互——turtle 和 tkinter 混在一起!

Turtle 窗口

请看下图,turtle窗口图标是一片小叶子,估计它就是继承自 tkinter 库。

tkinter 窗口

参阅了一些资料,发现 turtle 方法可直接在 tkinter 的画布Canvas上操作:

  

源代码

  1. from tkinter import *
  2. from turtle import RawTurtle
  3. def circ():
  4. tu.penup()
  5. tu.home()
  6. tu.clear()
  7. tu.speed(0)
  8. [x,y,R] = et1.get().split(',')
  9. try:
  10. x = int(x.replace('(',''))
  11. y = int(y.replace(')',''))
  12. R = int(R.strip())
  13. except:
  14. x,y,R = 0,0,50 #输入错误则赋予默认值
  15. tu.goto(x,y-R)
  16. tu.pendown()
  17. tu.circle(R)
  18. def rect():
  19. tu.penup()
  20. tu.home()
  21. tu.clear()
  22. tu.speed(0)
  23. tu.color('red', 'yellow')
  24. tu.begin_fill()
  25. [d,rad] = et2.get().split(',')
  26. try:
  27. d = int(d)
  28. rad = int(rad)
  29. except:
  30. d,rad = 200,216 #输入错误则赋予默认值
  31. tu.pendown()
  32. tu.back(d//5)
  33. while True:
  34. tu.forward(d)
  35. tu.left(rad)
  36. if abs(tu.pos()[0]+d//5)<0.1 and abs(tu.pos()[1])<0.1:
  37. break
  38. tu.end_fill()
  39. def taiji():
  40. tu.penup()
  41. tu.home()
  42. tu.clear()
  43. tu.speed(0)
  44. d = et3.get()
  45. try:
  46. d = int(d)
  47. except:
  48. d = 120 #输入错误则赋予默认值
  49. tu.hideturtle()
  50. tu.goto(d//2,-d)
  51. tu.pendown()
  52. tu.begin_fill()
  53. tu.color('black','black')
  54. tu.circle(d,extent=180)
  55. tu.circle(d//2,extent=180)
  56. tu.circle(-d//2,extent=180)
  57. tu.end_fill()
  58. tu.circle(-d,extent=180)
  59. tu.penup()
  60. tu.goto(d//2,-d//6*4)
  61. tu.pendown()
  62. tu.begin_fill()
  63. tu.fillcolor("black")
  64. tu.circle(d//5,extent=360)
  65. tu.end_fill()
  66. tu.penup()
  67. tu.goto(d//2,d//3)
  68. tu.pendown()
  69. tu.begin_fill()
  70. tu.fillcolor("white")
  71. tu.circle(d//5,extent=360)
  72. tu.end_fill()
  73. tu.penup()
  74. def main():
  75. global tu,et1,et2,et3
  76. root = Tk()
  77. root.geometry('520x520+150+300')
  78. root.title('turtle在tkinter.Canvas上的操作')
  79. root.resizable(False, False)
  80. canvas = Canvas(root, width=640, height=400)
  81. canvas.pack()
  82. tu = RawTurtle(canvas)
  83. tu.hideturtle()
  84. et1 = Entry(root, width=12)
  85. et1.place(x = 30, y = 480)
  86. et1.insert(0,'(50,-20), 100')
  87. bt1 = Button(root,text=' 画圆 ',command=circ)
  88. bt1.place(x = 60, y = 425)
  89. et2 = Entry(root, width=12)
  90. et2.place(x = 190, y = 480)
  91. et2.insert(0,'200, 216')
  92. bt2 = Button(root,text=' 多角星(或多边形) ',command=rect)
  93. bt2.place(x = 180, y = 425)
  94. et3 = Entry(root, width=12)
  95. et3.place(x = 360, y = 480)
  96. et3.insert(0,'120')
  97. bt3 = Button(root,text=' 太极 ',command=taiji)
  98. bt3.place(x = 380, y = 425)
  99. root.mainloop()
  100. if __name__ == '__main__':
  101. main()

turtle和tkinter混合使用

turtle和tkinter两者搭配使用,使得 turtle 的画图参数可以由 tkinter 的控件当场设置,这样就实现了turtle小海龟的现场互动,运行效果见图二。

三个Entry控件,分别设置: 
  1. 圆心坐标和圆的直径;
  2. 多边形的边长和边的转动角度;
  3. 太极图的外圆直径。

(本篇完)
 

一起学习交流 Python 的群二维码地址: http://qr01.cn/FHYKEa

推荐阅读