PR1*_*PR1 1 python 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 Thing:
    def __init__(self,val=None):
        self.val=val
    def change(self,val=None,win=None):
        self.val=val
        if win:win.destroy()
ABitmapImage不是小部件,如 aLabel或 a Button。它不能直接加入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将文件名映射到已加载的图像。
| 归档时间: | 
 | 
| 查看次数: | 1648 次 | 
| 最近记录: |