Python Tkinter:如何在打开新tk窗口时应用新背景图像?
我使用下面的代码(每个部分用不同的变量名)为每个tkinter窗口创建了一个背景图片。每个窗口都是在一个函数里启动的,单独运行时都没问题。
但是,当我从一个函数调用另一个函数时,第二个窗口却无法显示图片。(我也尝试在每个函数中导入所有相关内容。)如果我使用tk.destruct(),它是可以工作的,但如果我想保持窗口打开,或者用.withdraw()把它隐藏,图片就无法显示了,这样第二个窗口就没用了。
background_image=tk.PhotoImage(...)
background_label = tk.Label(parent, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
1 个回答
0
好的,我给你想了个解决办法。基本上,你只需要用 tk.Toplevel()
来创建第二个 tkinter 窗口,并确保它的“父窗口”是 root2
,这样图片就会出现在第二个窗口里。
我用按钮来显示图片,而你用的是标签,所以你可能想要改一下。不过按钮让我更容易打开一个新的 tk 窗口。我还用了 .pack()
,而不是 .place()
,因为对我来说这样更快。还有一点你可能需要知道的是,我用的是 python 3.3 和 Windows 系统,所以你可能需要把 tkinter
的 T 大写。
import tkinter as tk
root1 = tk.Tk()
def new_window():
root2 = tk.Toplevel()
# click the last button and all tk windows close
def shutdown():
root1.destroy()
root2.destroy()
background_image2 = tk.PhotoImage(file = '...')
background_button2 = tk.Button(root2, image = background_image2, command = shutdown)
background_button2.pack()
root2.mainloop()
background_image1 = tk.PhotoImage(file = '...')
# have used a button not a label for me to make another tk window
background_button1 = tk.Button(root1, image = background_image1, command = new_window)
background_button1.pack()
root1.mainloop()
@user2589273 下次你可以多加一些代码,这样别人就能更容易地给出答案,并且更符合你的需求,这只是个建议。希望这对你有帮助。