为什么我不能将位图图像或照片图像 tkinter 网格化?

Why can't I grid a bitmap image or photo image tkinter?

我有这段代码,它使用了 tkinter 位图图像:

def ask(msg='Question?',title='Question'):
    root=Tk()
    thing=Thing()
    root.title(title)
    imgw=BitmapImage(root,file='Question.xbm')
    root.iconbitmap('Question.ico')
    imgw.grid(rowspan=2,padx=5,pady=5,sticky=NSEW)
    msgw=Label(root,text=msg)
    msgw.grid(column=1,padx=10,pady=5,sticky=NSEW,columnspan=2)
    button1=Button(root,text='Yes',command=lambda:thing.change('Yes',root),underline=0)
    button1.grid(column=1,row=1,padx=5,pady=5,sticky=NSEW)
    button1.focus_set()
    button2=Button(root,text='No',command=lambda:thing.change('No',root),underline=0)
    button2.grid(column=2,row=1,padx=5,pady=5,sticky=NSEW)
    root.bind('Key-y',lambda:thing.change('Yes',root))
    root.bind('Key-n',lambda:thing.change('No',root))
    root.mainloop()
ask()

...但我无法将位图图像网格化。我试过 poth 照片图像和位图图像,但他们都说:

Traceback (most recent call last):
File "E:\gui.py", line 18, in <module>
ask()
File "E:\gui.py", line 7, in ask
imgw.grid(rowspan=2,padx=5,pady=5,sticky=NSEW)
AttributeError: 'BitmapImage' object has no attribute 'grid'

我正在使用 Python 3.4.2。有没有办法做到这一点,或者这只是 tkinter 中的一件烦人的事情?

顺便说一句,这里是 Thing class:

class Thing:
    def __init__(self,val=None):
        self.val=val
    def change(self,val=None,win=None):
        self.val=val
        if win:win.destroy()

BitmapImage 不是小部件,如 LabelButton。不能直接加root,用grid布局。相反,您必须将其添加到例如另一个 Label(或者如果您愿意,您用于问题的相同 Label)。

root=Tk()

imgw = BitmapImage(file='Question.xbm')            # no 'root' parameter
imgLabel = Label(root,image=imgw)                  # wrap the BitmapImage
imgLabel.grid(rowspan=2,padx=5,pady=5,sticky=NSEW) # layout the label

msgw=Label(root,text="Question")
msgw.grid(column=1,padx=10,pady=5,sticky=NSEW,columnspan=2)
button1=Button(root,text='Yes')
button1.grid(column=1,row=1,padx=5,pady=5,sticky=NSEW)
button2=Button(root,text='No')
button2.grid(column=2,row=1,padx=5,pady=5,sticky=NSEW)
root.mainloop()

另请注意,即使在标签中使用此类图像也容易被垃圾回收。为防止这种情况,您应该使 BitmapImage 成为全局变量,或将其放入全局容器中,例如dict 将文件名映射到已加载的图像。