Issue
This Content is from Stack Overflow. Question asked by Seminet
Hello I am trying to change background by button on tkinter. I have a button that changes background of mainWindow but when button pressed it doesn’t change immediately. I think tk.update()
command is useless because I made too much test with it and nothing happened.
Here’s my code:
import tkinter as tk
def ChangeBg():
global bgColor
bgColor = 'white'
mainWindow.update()
bgColor = 'black'
root = tk.Tk()
mainWindow = tkToplevel()
mainWindow.geometry('500x500')
mainWindow.config(bg=bgColor)
btn = tk.Button(mainWindow, text='change background', command=ChangeBg)
btn.pack()
tk.mainloop()
I guess you will say “Why don’t you just use mainWindow.config(bg=bgColor)
?”. Because in my main code I have to store color in variables and there will be a lot more widgets. Like generalBtnColor, generalForeground, generalTextColor
. I can write a lot of codes for update all widgets itself but this is Python and I believe there is a short way.
Solution
I added mainWindow.config(bg='white')
. Also changed in line 11 and 14.
import tkinter as tk
def ChangeBg():
global bgColor
mainWindow.config(bg='white')
mainWindow.update()
root = tk.Tk()
mainWindow = tk.Toplevel()
mainWindow.geometry('500x500')
mainWindow.config(bg = 'black')
btn = tk.Button(mainWindow, text='change background', command=ChangeBg)
btn.pack()
tk.mainloop()
Output:
Current black:
After changing to white:
This Question was asked in StackOverflow by Seminet and Answered by toyota Supra It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.