我是Python的入门程序员。我正在使用Tkinter库来创建带有下拉菜单的窗口。在下拉菜单中选择该项时,我创建了一个用于显示国家标志的标签。但是出了点问题,什么也没发生。这是我的代码,我将非常感谢谁帮助我处理和修复它。
from tkinter import *
root = Tk()
root.geometry('500x450+450+150')
root.title('Python Program')
menu = Menu(root)
root.config(menu=menu)
def callFlag():
photo = PhotoImage('image.png')
flag = Label(root, text='teste', image=photo)
flag.pack()
subMenu = Menu(menu, tearoff=0)
menu.add_cascade(label='Bandeiras', menu=subMenu)
subMenu.add_command(label='Mongólia', command=callFlag)
subMenu.add_command(label='Opção 2', command=callFlag)
subMenu2 = Menu(menu, tearoff=0)
menu.add_cascade(label='Menu 2', menu=subMenu2)
subMenu2.add_command(label='Opção 1', command=callFlag)
subMenu2.add_command(label='Opção 2', command=callFlag)
subMenu2.add_separator()
subMenu2.add_command(label='Exit', command=exit)
root.mainloop()
答案 0 :(得分:0)
这对您有用吗?
from tkinter import *
root = Tk()
root.geometry('500x450+450+150')
root.title('Python Program')
menu = Menu(root)
root.config(menu=menu)
def callFlag():
photo = PhotoImage(file='image.png')
flag = Label(root, text='teste', image=photo)
flag.image = photo
flag.pack()
subMenu = Menu(menu, tearoff=0)
menu.add_cascade(label='Bandeiras', menu=subMenu)
subMenu.add_command(label='Mongólia', command=callFlag)
subMenu.add_command(label='Opção 2', command=callFlag)
subMenu2 = Menu(menu, tearoff=0)
menu.add_cascade(label='Menu 2', menu=subMenu2)
subMenu2.add_command(label='Opção 1', command=callFlag)
subMenu2.add_command(label='Opção 2', command=callFlag)
subMenu2.add_separator()
subMenu2.add_command(label='Exit', command=exit)
root.mainloop()
当函数退出时,通过保留对photo
(flag.image = photo
)的额外引用,似乎可以避免Python的垃圾回收。
或者,您可以定义图像和标志以及其他所有内容,并在pack()
中传递标志的add_command
函数:
from tkinter import *
root = Tk()
root.geometry('500x450+450+150')
root.title('Python Program')
menu = Menu(root)
root.config(menu=menu)
photo = PhotoImage(file='image.png')
flag = Label(root, text='teste', image=photo)
subMenu = Menu(menu, tearoff=0)
menu.add_cascade(label='Bandeiras', menu=subMenu)
subMenu.add_command(label='Mongólia', command=flag.pack)
subMenu.add_command(label='Opção 2', command=flag.pack)
subMenu2 = Menu(menu, tearoff=0)
menu.add_cascade(label='Menu 2', menu=subMenu2)
subMenu2.add_command(label='Opção 1', command=flag.pack)
subMenu2.add_command(label='Opção 2', command=flag.pack)
subMenu2.add_separator()
subMenu2.add_command(label='Exit', command=exit)
root.mainloop()