简体   繁体   中英

How to display and change an icon inside a python Tk Frame

I have a python Tkinter Frame that displays several fields. I want to also add an red/yellow/green icon that will display the status of an external device.
The icon is loaded from a file called ICON_LED_RED.ico.

  1. How do I display the icon in my frame?
  2. How do I change the icon at runtime? For example replace BitmapImage('RED.ico') with BitmapImage('GREEN.ico')

Here is some code that is not working:

class Application(Frame):

  def __init__(self,  master=None):

    Frame.__init__(self, master)
    self.pack()
    self.createWidgets()


  def createWidgets(self):

    #  ...other frame code.. works just fine.
    self.OKBTN = Button(self)
    self.OKBTN["text"] = "OK"
    self.OKBTN["fg"]   = "red"
    self.OKBTN["command"] =  self.ok_btn_func
    self.OKBTN.pack({"side": "left"})

    # when I add the following the frame window is not visible
    # The process is locked up such that I have to do a kill -9 
    self.statusFrame = Frame(self, bd=2, relief=RIDGE)
    Label(self.statusFrame, text='Status:').pack(side=LEFT, padx=5)
    self.statIcon = BitmapImage('data/ICON_LED_RED.ico')
    Label (self.statusFrame, image=self.statIcon ).grid()
    self.statusFrame.pack(expand=1, fill=X, pady=10, padx=5) 

I use the following code to display an icon in tkinter

class dialog(Tk):
     def __init__(self):
        Tk.__init__(self)
        self.wm_iconbitmap('images/Icon.ico')

The problem is that you are mixing grid and pack in the same container. This is quite often the cause of a GUI freezing. The problem is, the grid manager resizes everything to fit, then the pack manager sees a change and resizes things to fit. The grid manager sees a change and resizes things to fit, and ...

You are using pack with the label that contains the text "Status:", but grid with the label that has the image.

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