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.
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:
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.