[英]Bouncing dvd logo in python tkinter
我正在嘗試在 tkinter 中制作一個彈跳的 DVD 徽標,但我真的不知道如何制作它,它與一個球一起使用,徽標不會移動。 標志
# 1) create main window
from tkinter import *
from PIL import ImageTk, Image
fen = Tk()
fen.title('AllTech - Bouncing ball')
fen.resizable(False, False)
# 2) create canvas and ball
WIDTH, HEIGHT = 400, 300
canvas = Canvas(fen, width=WIDTH, height=HEIGHT)
canvas.pack()
img = ImageTk.PhotoImage(Image.open("dvd.gif"))
# ball = canvas.create_oval(10, 10, 50, 50, fill='black')
# 3) move the ball
xspeed = yspeed = 3
frame = Frame(fen, width=600, height=400)
frame.pack()
frame.place(anchor='center', relx=0.5, rely=0.5)
label = Label(frame, image = img)
label.pack()
def moveBall():
global xspeed, yspeed
canvas.move(canvas, xspeed, yspeed)
(leftPos, topPos, rightPos, bottomPos) = canvas.coords(img)
if leftPos <= 0 or rightPos >= WIDTH:
xspeed = -xspeed
if topPos <= 0 or bottomPos >= HEIGHT:
yspeed = -yspeed
img.after(30, moveBall)
canvas.after(30, moveBall)
fen.mainloop()
我試過球形廣告,但我不知道為什么,它沒有徽標。
您需要使用canvas.create_image()
放置圖像,然后您可以使用canvas.move()
移動圖像。
from tkinter import *
from PIL import ImageTk, Image
fen = Tk()
fen.title('AllTech - Bouncing ball')
fen.resizable(False, False)
WIDTH, HEIGHT = 400, 300
canvas = Canvas(fen, width=WIDTH, height=HEIGHT, bg="white")
canvas.pack()
img = ImageTk.PhotoImage(Image.open("dvd.gif"))
# put the image into canvas
logo = canvas.create_image(0, 0, image=img, anchor="nw")
xspeed = yspeed = 3
def moveLogo():
global xspeed, yspeed
# move the image
canvas.move(logo, xspeed, yspeed)
# get bounding box of the image
(leftPos, topPos, rightPos, bottomPos) = canvas.bbox(logo)
if leftPos <= 0 or rightPos >= WIDTH:
xspeed = -xspeed
if topPos <= 0 or bottomPos >= HEIGHT:
yspeed = -yspeed
canvas.after(30, moveLogo)
canvas.after(30, moveLogo)
fen.mainloop()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.