Reputation: 1
Actually I was building a notepad, I made a button which will inter change the color of text widget. But its not working nor it giving an error. Can someone explain why this is not working with a solution?
from tkinter import *
import tkinter.messagebox as tmsg
from tkinter import ttk
root = Tk()
root.geometry('450x500')
root.title('my notepad')
fonts = ['lucida','Arial']
fg_col,bg_col = 'black','white'
def darkmode():
global fg_col,bg_col
fg_col,bg_col='white','black'
Button(root,text='DARK Theme',bg = 'grey',command=darkmode).pack()
text = Text(root,font =(f'{fonts[0]}',18,'bold'),foreground = fg_col,background=bg_col).pack()
root.mainloop()
Upvotes: 0
Views: 1039
Reputation: 5541
Just prepare the 2 modes and use them as kwargs
. I got you started with something more encompassing than just foreground and background colors.
import tkinter as tk
root = tk.Tk()
root.geometry('450x500')
root.configure(bg='grey60')
root.title('my notepad')
#prepare base kwargs
common = dict(
font = 'arial 18 bold',
borderwidth = 0,
wrap = 'word', #or 'char', 'none'
relief = 'flat',
tabs = '1c',
highlightthickness = 2,
insertwidth = 4, #fat caret
insertofftime = 600, #caret slow blink
insertontime = 1200,
padx = 10, #thick padding
pady = 10,
blockcursor = False #make True for really fat cursor
)
#prepare light kwargs
lightmode = dict(
foreground = 'black',
background = 'white',
insertbackground = 'black', #caret color
selectforeground = 'white', #when text is selected
selectbackground = 'black', #~
highlightbackground = 'gray40', #highlight color when Text does NOT have focus
highlightcolor = 'gray80', #highlight color when Text has focus
)
#prepare dark kwargs
darkmode = dict(
foreground = 'white',
background = 'black',
insertbackground = 'white', #caret color
selectforeground = 'black', #when text is selected
selectbackground = 'white', #~
highlightbackground = 'gray80', #highlight color when Text does NOT have focus
highlightcolor = 'gray40', #highlight color when Text has focus
)
#not used but acts as an example
#that you can just keep copy/pasting these things
#and changing values
mcdonaldsmode = dict(
foreground = 'yellow',
background = 'red',
insertbackground = 'yellow', #caret color
selectforeground = 'red', #when text is selected
selectbackground = 'yellow', #~
highlightbackground = 'red', #highlight color when Text does NOT have focus
highlightcolor = 'yellow', #highlight color when Text has focus
)
#toggle modes
def toggle():
text.basemode = not text.basemode
text.configure(**lightmode) if text.basemode else text.configure(**darkmode)
tk.Button(root, text='Switch Theme', bg='grey60', fg='grey100', command=toggle).pack(anchor='e')
text = tk.Text(root, **lightmode, **common)
text.basemode = True #invent a switch to toggle
text.pack()
root.mainloop()
Upvotes: 2
Reputation: 13
Instead of editing the variables fg_col,bg_col
you should configure the widget:
def darkmode():
text.config(foreground="white", background='black')
Upvotes: 1