【问题标题】:Moving image in python tkinterpython tkinter中的移动图像
【发布时间】:2021-02-02 14:37:15
【问题描述】:

我正在编写一个简单的程序,我希望(球图像 png)在其中从墙上反弹。到目前为止,我已经写了这段代码:

import tkinter as tk

root = tk.Tk()

WIDTH = 500
HEIGHT = 500

canvas = tk.Canvas(root,bg="white",width=WIDTH,height=HEIGHT)
canvas.pack()

img = tk.PhotoImage(file="images/ball1.png")
ball = canvas.create_image(0,0,anchor="nw",image=img)

yspeed = 2
xspeed = 2

def move_ball():
    global xspeed,yspeed,ball
    canvas.move(ball,xspeed,yspeed)
    canvas.after(10,move_ball)

move_ball()
root.mainloop()

【问题讨论】:

  • 似乎没有任何代码让您尝试进行任何类型的边缘检测。

标签: python image animation tkinter png


【解决方案1】:

您可以使用coords 方法获取当前位置,然后对 4 面墙中的每面进行检查。这是第一个:

def move_ball():
    global xspeed,yspeed,ball
    xpos, ypos = canvas.coords(ball)
    if xpos + width_of_ball > WIDTH:
        # ball hit the right edge, reverse x direction
        xspeed *= -1
    canvas.move(ball,xspeed,yspeed)
    canvas.after(10,move_ball)

【讨论】:

    【解决方案2】:

    此答案与@Novel 答案相同(尽管我在看到他们的答案之前就写了它)。唯一的区别在于update 的逻辑并不期望您对其进行任何编辑,它会考虑水平和垂直方向,并且会补偿调整主窗口的大小。

    import tkinter as tk
    
    root = tk.Tk()
    root.title('Infinite Bounce Simulator')
    root.geometry('400x300+300+300')
    
    xspeed = 4
    yspeed = 3
    
    canvas = tk.Canvas(root, highlightthickness=0, bg='#111')
    canvas.pack(expand=True, fill='both')    
    
    ball   = canvas.create_oval((0, 0, 20, 20), fill='red')
    
    def update():
        global xspeed, yspeed, ball
        
        canvas.move(ball, xspeed, yspeed)
        
        #Left, Top, Right, Bottom coordinates
        l, t, r, b = canvas.coords(ball)
        
        #flip speeds when edges are reached
        if r > canvas.winfo_width()  or l < 0:
            xspeed = -xspeed 
        if b > canvas.winfo_height() or t < 0:
            yspeed = -yspeed           
            
        #do it all again in 10 milliseconds
        root.after(10, update)
        
        
    root.after_idle(update)    
    root.mainloop()
    

    【讨论】:

    • 如果您至少添加一个微小的解释,这个答案会更好,因此读者不必将您的代码与原始代码逐行​​和逐字符进行比较。跨度>
    • @BryanOakley 我同意,但是,这一切都太明显了,我觉得解释它会很愚蠢。我会添加一些东西。
    • 你为什么不在if x+w &gt; canvas.winfo_width() ... 中使用x1 而不是x+wy1y+h 相同。
    • @acw1668 ~ 显然,这太简单明了 :D。好眼力。
    猜你喜欢
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-14
    • 1970-01-01
    • 2015-06-04
    • 1970-01-01
    相关资源
    最近更新 更多