Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ลูกบอลเคลื่อนที่ใน Tkinter Canvas


Tkinter เป็นไลบรารี Python มาตรฐานที่ใช้สร้างแอปพลิเคชันที่ใช้ GUI ในการสร้างแอปพลิเคชันลูกบอลเคลื่อนที่อย่างง่าย เราสามารถใช้วิดเจ็ต Canvas ซึ่งให้ผู้ใช้เพิ่มรูปภาพ วาดรูปร่าง และวัตถุเคลื่อนไหวได้ แอปพลิเคชันมีองค์ประกอบดังต่อไปนี้

  • วิดเจ็ต Canvas สำหรับวาดรูปวงรีหรือลูกบอลในหน้าต่าง

  • ในการเคลื่อนลูกบอล เราต้องกำหนดฟังก์ชัน move_ball() . ในฟังก์ชัน คุณต้องกำหนดตำแหน่งของลูกบอลที่จะได้รับการอัปเดตอย่างต่อเนื่องเมื่อลูกบอลกระทบผนังผ้าใบ (ซ้าย ขวา บน และล่าง)

  • ในการอัปเดตตำแหน่งลูก เราต้องใช้ canvas.after(duration, function()) ซึ่งสะท้อนให้ลูกบอลเปลี่ยนตำแหน่งหลังจากช่วงเวลาหนึ่ง

  • สุดท้าย รันโค้ดเพื่อเรียกใช้แอปพลิเคชัน

ตัวอย่าง

# Import the required libraries
from tkinter import *

# Create an instance of tkinter frame or window
win=Tk()

# Set the size of the window
win.geometry("700x350")

# Make the window size fixed
win.resizable(False,False)

# Create a canvas widget
canvas=Canvas(win, width=700, height=350)
canvas.pack()

# Create an oval or ball in the canvas widget
ball=canvas.create_oval(10,10,50,50, fill="green3")

# Move the ball
xspeed=yspeed=3

def move_ball():
   global xspeed, yspeed

   canvas.move(ball, xspeed, yspeed)
   (leftpos, toppos, rightpos, bottompos)=canvas.coords(ball)
   if leftpos <=0 or rightpos>=700:
      xspeed=-xspeed

   if toppos <=0 or bottompos >=350:
      yspeed=-yspeed

   canvas.after(30,move_ball)

canvas.after(30, move_ball)

win.mainloop()

ผลลัพธ์

การเรียกใช้โค้ดด้านบนจะแสดงหน้าต่างแอปพลิเคชันที่จะมีลูกบอลเคลื่อนที่ในผืนผ้าใบ

ลูกบอลเคลื่อนที่ใน Tkinter Canvas