我正在尝试将图像实现到 tkinter 中的按钮中,当我尝试加载它时,图像和窗口加载需要超过 5 秒的时间。
我希望这样当单击下一个按钮时,图像几乎立即加载,以便我可以更快地调试和测试代码(而不是每次都浪费 6 秒)。 有没有更好的方法(或更快)来加载这些图像?
from tkinter import *
import math
from PIL import Image, ImageTk
import time
root = Tk()
# Tkinter stuff
root.title("Projectile motion")
root.geometry("800x500")
root.resizable(False, False)
scale_label = None
def switch():
page1.grid_forget() # Hide the welcome page
page2.grid(row=0, column=0, sticky="nsew") # Show the instructions page
page1 = Frame(root, width=800, height=500)
page2 = Frame(root, width=800, height=500, bg = "azure3")
page1.grid(row=0, column=0, sticky="nsew")
page2.grid(row=0, column=0, sticky="nsew")
# main page stuff
main_window_title = Label(page1, text="Projectile Motion Simulation", font=("Times New Roman bold", 35))
main_window_title.place(relx=0.13, rely=0.26)
main_window_button = Button(page1, text="Start", font=("Arial bold", 15), background= "#ff0000", activebackground= "#f08080", command=switch,
height=4, width=20)
main_window_button.place(relx=0.5, rely=0.6, anchor="center")
# page 2/ instructions page
welcome_text = Label(page2, text="Welcome to Projectile Motion simulation",bg = "azure3", font=("Times New Roman bold", 30))
welcome_text.place(relx = 0,rely = 0)
htp_text = Label(page2, text="How to play?", bg = "azure3" ,font=("Times New Roman", 25))
htp_text.place(relx = 0, rely = 0.1)
instruction_text = ("1) Use sliders, checkboxes, and buttons to adjust the simulation\n"
"2) Press 'Launch' button to show output values\n"
"3) Press checkboxes to show values on animation window\n"
"4) Press 'projectile 1' and 'projectile 2' to switch between projectiles \n"
"5) Press 'Explanation' button to get the theory on projectile motion\n"
"6) Press 'Quiz' button to try a quiz on projectile motion\n"
"7) Press back button to close window")
htp2_text = Label(page2, text=instruction_text,font=("Times New Roman", 20), bg = "azure3",justify='left', anchor='w')
htp2_text.place(relx = 0,rely = 0.2)
def selection_window():
selection_window = Toplevel()
selection_window.title("Selection page")
selection_window.config(width=500, height=500)
selection_window.resizable(False, False)
selection_window.bind("<Destroy>", enable_button)
click_btn= PhotoImage(file="scenario 1.png")
click_btn = click_btn.zoom(25)
click_btn = click_btn.subsample(40)
click_btn2= PhotoImage(file="scenario 2.png")
click_btn2 = click_btn2.zoom(25)
click_btn2 = click_btn2.subsample(40)
global button1
button1 = Button(selection_window, image = click_btn,command=vertical_animation)
button1.image = click_btn
button1.grid(row=0, column=0)
global button2
button2 = Button(selection_window,image = click_btn2 ,command=lambda: animation_window(1))
button2.image = click_btn2
button2.grid(row=0, column=1)
root.withdraw()
不幸的是没有办法做到这一点。创建 tkimage 需要很多时间。如果你有一个包含数百帧的 gif...
但这里有一些你可能可以考虑的事情:
.zoom()
和 .subsample()
。更少的工作,更快的速度。 tkimages = (tk.PhotoImage(file=img) for img in list_images_png)
button.configure(image=next(tkimages))