Search code examples
pythontkintertogglepython-2.x

How to create a tkinter toggle button?


I've been working on a text editor using Tkinter in Python 2.7. A feature that I'm trying to implement is the Night Mode, where the user can toggle between a black background and a light one, that switches from light to dark with a click of the toggle button.

from Tkinter import *

from tkSimpleDialog import askstring

from tkFileDialog   import asksaveasfilename
from tkFileDialog import askopenfilename

from tkMessageBox import askokcancel

Window = Tk() 
Window.title("TekstEDIT")
index = 0

class Editor(ScrolledText):

    Button(frm, text='Night-Mode',  command=self.onNightMode).pack(side=LEFT)

    def onNightMode(self):
    if index:
        self.text.config(font=('courier', 12, 'normal'), background='black', fg='green')

    else:
        self.text.config(font=('courier', 12, 'normal'))

    index = not index   

However, on running the code, it is always in the night mode and the toggle doesn't work. Help. Source Code: http://ideone.com/IVJuxX


Solution

  • The background and fg are set only in the if-clause. You need to set them also in the else clause:

    def onNightMode(self):
        if index:
            self.text.config(font=('courier', 12, 'normal'), background='black', fg='green')
    
        else:
            self.text.config(font=('courier', 12, 'normal'))
    
        index = not index
    

    i.e.,

    else:
        self.text.config(font=('courier', 12, 'normal'), background='green', fg='black')