Change button color on if clause - Tkinter

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • indeed
    New Member
    • Jul 2016
    • 2

    Change button color on if clause - Tkinter

    Hi guys,
    I'm new to Python, and now I'm trying to make a simple GUI with Tkinter.

    So.. I want to change a button's color based on if file is selected clause:

    Code:
    import Tkinter, tkFileDialog, Tkconstants 
    from Tkinter import * 
    
    version = '1.0'
    filetext= 'Select Landsat 8 OLI'
    def openFile():
        filename = tkFileDialog.askopenfilename(parent=root,initialdir='/home/',title=filetext ,filetypes=[('ERDAS IMAGINE', '.img')]) ## filename not filehandle
        filebut["text"]= str(filename) if filename else filetext
    
    root = Tk() 
    root.title('NDVI GUI ' + version)
    root.geometry('300x100')
    #Options for buttons
    button_opt = {'fill': Tkconstants.BOTH, 'padx': 5, 'pady': 5}
    
    #Define asking watermark file button
    filebut = Button(root, text = filetext, fg = 'black', command= openFile)
    filebut
    filebut.pack(**button_opt)
    root.mainloop()
    I was wondering if I could change bg to green of the
    Code:
    filebut = Button
    based on the function
    Code:
    openFile
    clause
    Code:
    if filename else filetext
    Something like if filename == None:
    bg = "green"
    else pass

    I know that I probably this is very bad written but just wanted to see if could be done. Thank you!
  • dwblas
    Recognized Expert Contributor
    • May 2008
    • 626

    #2
    To change any widget's color, including a button, you use the config function with a "background " or foreground" parameter, some_button.con fig(background= "green"), or access the dictionary directly, some_button["background "]="green" http://effbot.org/tkinterbook/button.htm

    Comment

    • indeed
      New Member
      • Jul 2016
      • 2

      #3
      Thank you, I found that link myself. But I can't make it work..
      What I want to do is to change button bg color when a condition is met. If file is selected change to green, if not don't (pass).

      Comment

      Working...