Tkinter 畫布中的運動小球


Tkinter 是用於建立基於 GUI 的應用程式的標準 Python 庫。為了建立一個簡單的運動小球應用程式,我們可以使用 Canvas 視窗小部件,它允許使用者新增影像、繪製形狀並對物件進行動畫。該應用程式具有以下元件,

  • 一個 Canvas 視窗小部件,用於在視窗中繪製橢圓或球。

  • 為了移動小球,我們必須定義一個函式 move_ball()。在該函式中,你必須定義小球的位置,當小球擊中 Canvas 牆壁(左、右、上和下)時,該位置將不斷更新。

  • 為了更新小球位置,我們必須使用 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()

輸出

執行以上程式碼將顯示一個應用程式視窗,其中將有一個運動的小球在 Canvas 中。

更新於:18-6-2021

2 千次以上瀏覽

開啟您的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.