Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 591
Potato_head Avatar asked Apr 18 '14 10:04

Potato_head


People also ask

How do you toggle frames in Tkinter?

One way to switch frames in tkinter is to destroy the old frame then replace it with your new frame. I have modified Bryan Oakley's answer to destroy the old frame before replacing it. As an added bonus, this eliminates the need for a container object and allows you to use any generic Frame class.

How do you create a button on a Tkinter canvas?

Canvas widget is one of the versatile widgets in the Tkinter library. You can use canvas to draw different shapes, arcs, and objects to animate within the canvas. To create a button on a Tkinter Canvas, simply pass the parent as the canvas in place of a parent in the Button constructor.

What does Mainloop () do in Tkinter?

mainloop() tells Python to run the Tkinter event loop. This method listens for events, such as button clicks or keypresses, and blocks any code that comes after it from running until you close the window where you called the method.

Which is toggle button?

A toggle button allows the user to change a setting between two states. You can add a basic toggle button to your layout with the ToggleButton object. Android 4.0 (API level 14) introduces another kind of toggle button called a switch that provides a slider control, which you can add with a Switch object.


3 Answers

You can import tkinter library (Use capital letter for python 2.7):

import Tkinter 

Create tkinter objects...

root = tk.Tk()

...and tkinter button

toggle_btn = tk.Button(text="Toggle", width=12, relief="raised")
toggle_btn.pack(pady=5)
root.mainloop()

Now create a new command button called "toggle" in order to create the effect of "toggle" when you press playing on the relief property (sunken or raised) :

def toggle():

    if toggle_btn.config('relief')[-1] == 'sunken':
        toggle_btn.config(relief="raised")
    else:
        toggle_btn.config(relief="sunken")

At the end apply this behaviour on your button:

toggle_btn = tk.Button(text="Toggle", width=12, relief="raised", command=toggle)
like image 121
Albe Avatar answered Oct 15 '22 08:10

Albe


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')
like image 29
unutbu Avatar answered Oct 15 '22 09:10

unutbu


Here's a code snippet that will help you with the toggle button animation if you would like to. You only need to add the functions that you want to execute when clicking of course, that's up to you.

'''
    import tkinter as tk

    # --- functions ---

    def move(steps=10, distance=0.1):
        if steps > 0:
            # get current position
            relx = float(frame.place_info()['relx'])

            # set new position
            frame.place_configure(relx=relx+distance)

            # repeate it after 10ms
            root.after(10, move, steps-1, distance)

    def toggle(event):
        if button["text"] == "Yes":
            move(25, 0.02)  # 50*0.02 = 1
            button["text"] = "No"
            print("Clicked on yes")
        elif button["text"] == "No":
            move(25, -0.02)
            button["text"] = "Yes"
            print("Clicked on no")


    # --- main --

    root = tk.Tk()

    frame = tk.Frame(root, background='red')
    frame.place(relx=0, rely=0, relwidth=0.5, relheight=1)

    # to center label and button
    #frame.grid_columnconfigure(0, weight=1)
    #frame.grid_rowconfigure(0, weight=1)
    #frame.grid_rowconfigure(3, weight=1)




    button = tk.Button(frame, text='Yes',width=5,height=1)
    button.place(relx=0.25,rely=0.5,relwidth=0.5, relheight=0.1)
    button.bind("<Button-1>",toggle)


    root.mainloop()
like image 32
Amrou Avatar answered Oct 15 '22 08:10

Amrou