简体   繁体   中英

python tkinter how to use image button?

I am making image button. My code is below.

button1=Button(root,width=80,height=200)
image1=PhotoImage(file="/home/imagefolder/1.png")
button1.config(image=self.image1)
button1.image=image1
button.pack(side=left)

When i don't have file "1.png", I want to set button as empty. But now I have an error:

tkinter.TclError: couldn't open "/...". no such file or directory.

How can I solve it?

You can just add an error check:

button1=Button(root,width=80,height=200)
try:
    image1=PhotoImage(file="/home/imagefolder/1.png")
    button1.config(image=self.image1)
    button1.image = image
except TclError:
    pass
button1.pack(side=left)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM