Hy! Tkinter에서 만든 GUI에서 이미지를 배경으로 사용하려고합니다. 이 프로젝트의 다른 프레임에서 동일한 코드로 잘 작동하지만 다른 프레임에서 작동하고 싶지 않습니다. 오류가 발생하지 않고 프레임이 비어 있습니다. 도와 주셔서 감사합니다!
여기에서 그림을 배경으로 사용할 수 있습니다.
def main_screen():
global screen
screen = 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()
도와 주셔서 감사합니다!
아주 간단해야합니다. 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 인스턴스에 대한 변수가 함수 호출이 끝난 후 사라지기 때문에 해당 참조를 설정하는 것이 중요합니다.
추신 : 마스터 위젯에 대해 더 명확하고 작은 성능 향상을 위해 위젯을 초기화 할 때 항상 마스터 위젯을 제공하십시오. tkinter는 또한 마지막으로 생성 된 Tk 인스턴스를 마스터 자체로 자동 할당하지만 a) 불필요한 컴퓨팅 능력이 필요하고 b) 어떤 위젯이 다른 위젯의 자식인지 추적하는 것이 더 쉽습니다. ;)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다