By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,986 Members | 2,030 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,986 IT Pros & Developers. It's quick & easy.

Change button color on if clause - Tkinter

P: 2
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:

Expand|Select|Wrap|Line Numbers
  1. import Tkinter, tkFileDialog, Tkconstants 
  2. from Tkinter import * 
  4. version = '1.0'
  5. filetext= 'Select Landsat 8 OLI'
  6. def openFile():
  7.     filename = tkFileDialog.askopenfilename(parent=root,initialdir='/home/',title=filetext ,filetypes=[('ERDAS IMAGINE', '.img')]) ## filename not filehandle
  8.     filebut["text"]= str(filename) if filename else filetext
  10. root = Tk() 
  11. root.title('NDVI GUI ' + version)
  12. root.geometry('300x100')
  13. #Options for buttons
  14. button_opt = {'fill': Tkconstants.BOTH, 'padx': 5, 'pady': 5}
  16. #Define asking watermark file button
  17. filebut = Button(root, text = filetext, fg = 'black', command= openFile)
  18. filebut
  19. filebut.pack(**button_opt)
  20. root.mainloop()
I was wondering if I could change bg to green of the
Expand|Select|Wrap|Line Numbers
  1. filebut = Button
based on the function
Expand|Select|Wrap|Line Numbers
  1. openFile
Expand|Select|Wrap|Line Numbers
  1. 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!
Jul 8 '16 #1
Share this Question
Share on Google+
2 Replies

Expert 100+
P: 614
To change any widget's color, including a button, you use the config function with a "background" or foreground" parameter, some_button.config(background="green"), or access the dictionary directly, some_button["background"]="green"
Jul 8 '16 #2

P: 2
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).
Jul 9 '16 #3

Post your reply

Sign in to post your reply or Sign up for a free account.