繁体   English   中英

Python Tkinter在按下按钮时移动图像

[英]Python Tkinter Moving images on buttonpress

我正在尝试在图像上写一个Tkinter代码,如果按下名为“ Rain”的按钮,则好像下雨了。

我还不能确定图像移动部件的工作方式,但是问题是,当我单击“雨”按钮时,它会写->“雨”,但它不会出现在画布上。

另一个有趣的是,当我服用

这是我的代码:

 root = Tk()

#Create the canvas
canvas = Canvas(width=1000, height=1000)
canvas.pack()

#This is the part that does not work
#Nothing appears when this function is called 
def Rain():
    image3 = "Drops.png"
    drops = PhotoImage(file = image3)
    drops_background = canvas1.create_image(100, 100, image=drops)
    while True:
        canvas1.move(drops_background, 10, 10)
    print("Rain")

#Adding a button and making it to use function "Rain"
frame = Frame(root)
frame.pack()
button1 = Button(frame, text = "Rain", command = Rain, fg = "red" ).pack(side = LEFT)
root.mainloop()

另一个有趣的事情是,如果我将这部分放在功能之外,它将开始工作。

image3 = "Drops.png"
drops = PhotoImage(file = image3)
drops_background = canvas1.create_image(100, 100, image=drops)

如果有人可以告诉我这里出了什么问题,或者至少将我指出正确的方向,那将对我有很大帮助。

PhotoImage存在问题(或者PILPillow模块中存在问题)-必须将PhotoImage分配给全局变量。 如果将PhotoImage分配给局部变量,则Garbage Collector会将其从内存中删除。

与全工作示例after

import Tkinter as tk
import random

# --- globals ---

drops_background = None
drops = None

# --- functions ---

def rain():
    global drops_background
    global drops

    filename = "Drops.png"

    drops = tk.PhotoImage(file=filename) # there is some error in PhotoImage - it have to be assigned to global variable

    drops_background = canvas.create_image(100, 100, image=drops)

    # move after 250ms
    root.after(250, move) # 250ms = 0.25s


def move():
    global drops_background

    # TODO: calculate new position
    x = random.randint(-10, 10)
    y = random.randint(-10, 10)

    # move object
    canvas.move(drops_background, x, y)

    # repeat move after 250ms
    root.after(250, move) # 250ms = 0.25s

# --- main ----

root = tk.Tk()

#Create the canvas
canvas = tk.Canvas(root, width=1000, height=1000)
canvas.pack()

#This is the part that does not work
#Nothing appears when this function is called 
#Adding a button and making it to use function "Rain"
frame = tk.Frame(root)
frame.pack()

button1 = tk.Button(frame, text="Rain", command=rain, fg="red" )
button1.pack(side=tk.LEFT)

root.mainloop()

after给定时间添加函数和时间后,从该列表中运行mainloop运行函数。

after期望函数名称不带()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM