呵呵!我正在嘗試在Tkinter中創建的GUI中使用圖像作為背景。它可以在此項目中的不同幀上使用相同的代碼,但它不希望在不同的幀中工作。我沒有收到任何錯誤,框架只是空白。感謝您的幫助!在這里,我可以很好地使用圖片作為背景:def main_screen():global screenscreen = Tk()screen.geometry("600x750")screen.configure(background="#022140")screen.title("Hermes")filename = PhotoImage(file="background.png")filename_small = filename.subsample(2, 2)background_label = Label(image=filename_small)background_label.place(x=1, y=1, relwidth=1, relheight=1)login_button = Button(text="Login", bg="#022140", height="2", width="30", command=login, highlightbackground='#494B68')screen.mainloop()但在這里它不起作用:def login_sucess(): global screen3 screen3 = Toplevel(screen) screen3.geometry("500x400") filename = PhotoImage(file="main_theme.png") filename_small = filename.subsample(2, 2) background_label = Label(screen3, image=filename_small) background_label.place()感謝您的幫助!
1 回答

臨摹微笑
TA貢獻1982條經驗 獲得超2個贊
它應該非常簡單。當您在 tkinter 中處理圖像時,您始終需要在使用該圖像的小部件上設置對該圖像的引用。換句話說,執行如下操作:
from tkinter import Tk,Label,PhotoImage
root = Tk()
img = PhotoImage(file='background.png')
small_img=img.subsample(2, 2)
background_label = Label(root, image=small_img)
background_label.img=img
background_label.place(x=0, y=0, relheight=1, relwidth=1)
root.mainloop()
特別是當您創建將圖像保存在函數范圍或類似內容中的 Label 時,設置該引用非常重要,因為在函數調用結束后,指向該 Labels 實例的變量將消失。
PS:為了更清楚地了解主小部件,并且對于小部件的小性能改進,在初始化時始終會給小部件一個主小部件。我知道tkinter還會自動將最后創建的Tk實例分配為主實例本身,但是a)是否需要不必要的計算能力,b)是否更容易跟蹤哪個小部件是另一個小部件的子級等等。;)
添加回答
舉報
0/150
提交
取消