Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop the button from changing its relief when I press it. (Tkinter)

Tags:

python

tkinter

Greatings! I'm trying to do a simple calculator with Tkinter, what I want is that when I press a button it does not change relief and keeps being FLAT. The problem is that it keeps changing to GROOVE.

Here is the code line:

button1 = tk.Button(self, text="1", command=lambda: self.config(relief=FLAT), relief=FLAT,
                            font=myfont, bg="ghost white", activebackground="LightSteelBlue2")

I would appreciate the help.

EDIT

What I want the button to do is something like this, like the buttons of the Windows Calculatorenter image description here

like image 452
SaturnDev Avatar asked Dec 10 '25 22:12

SaturnDev


2 Answers

You can use a label if you want it to stay flat even when being pressed. Thought I am not sure why you do not want some visual q to show it has been clicked.

Here is an example using A button and a Label. Notice the label works like a button when we use bind() but without visually changing.

import tkinter as tk


def do_something(value):
    print(value)


root = tk.Tk()
# Normal button behavior.
tk.Button(root, text="Button 1", relief='flat', bg="ghost white",
          activebackground="LightSteelBlue2",
          command=lambda: do_something("Button 1")).pack()

# Is a button but does not change visuals when clicked due to state='disabled' and bind combination.
# Downside the text is greyed out.
button_2 = tk.Button(root, text="Button 2", relief='flat', bg="ghost white",
                     activebackground="LightSteelBlue2", state='disabled')
button_2.pack()
button_2.bind("<Button-1>", lambda e: do_something("Button 2"))

# Is a label but works like a button due to bind.
# This method should fit your needs.
label_1 = tk.Label(root, text="Label 1", bg="ghost white", activebackground="LightSteelBlue2")
label_1.pack()
label_1.bind("<Button-1>", lambda e: do_something("Label 1"))

root.mainloop()

Update:

Based on your comments below "I want the button to change its color when is pressed and when is unpressed it returns to its normal state." this is how I would get the functionality you are looking for.

import tkinter as tk


def change_color(event):
    event.widget.config(bg='green')
    entry.insert('end', event.widget['text'])


def change_back(event):
    event.widget.config(bg='ghost white')


root = tk.Tk()
num_pad = [[1, 2, 3],
           [4, 5, 6],
           [7, 8, 9]]

entry = tk.Entry(root, width=50)
entry.grid(row=0, column=0)

pad_frame = tk.Frame(root)
pad_frame.grid(row=1, column=0)
# Is a label but works like a button due to bind.
# This method should fit your needs.
for ndex, sub_list in enumerate(num_pad):
    for sub_ndex, sub_value in enumerate(sub_list):
        lbl = tk.Label(pad_frame, text=sub_value, bg="ghost white", activebackground="LightSteelBlue2",
                       height=2, width=3)
        lbl.grid(row=ndex, column=sub_ndex, padx=2, pady=2)
        lbl.bind("<Button-1>", change_color)
        lbl.bind("<ButtonRelease-1>", change_back)
        lbl.bind("<Leave>", change_back)
root.mainloop()
like image 155
Mike - SMT Avatar answered Dec 13 '25 11:12

Mike - SMT


It might seem like extra trouble, but you can do this with ttk by using ttk.Style().

You can keep most of your buttons setup logic in style.config and you can specify state-specific variations for one or more of a style's configuration options with style.map

import tkinter as tk
from tkinter import ttk

# You can put this in function and call it when your main app initializes.
def configure_styles():
    style = ttk.Style()
    
    # General configuration
    style.configure(
        'MyButton.TButton',
        font=('Helvetica', 12, 'bold'),
        background='ghost white',
        padding=6,
        anchor='center',
    )
    
    # State-specific variations
    style.map(
        'MyButton.TButton',
        background=[
            ('active', '!pressed', 'ghost white'),
            ('active', 'pressed', 'LightSteelBlue2'),  # Change colors when pressed.
        ],
        relief=[
            ('pressed', tk.FLAT),  # Stay flat when pressed
            ('!pressed', tk.FLAT),
        ],
    )

In your main application you can access the style you created and apply it to as many buttons as you wish via the style parameter.

In the example we created a style for type Button '.TButton' and named it 'MyButton'

button = ttk.Button(self, text="1", style="MyButton.TButton", command=lambda: self.do_stuff)
button.pack(pady=10)

Your main app could then look something like this:

class MainApp(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("Styled ttk Widgets App")
        self.geometry("400x200")
        self.config(background='ghost white')

        configure_styles()  # Initialize the styles

        button = ttk.Button(self, text="1", style="MyButton.TButton", command=lambda: self.do_stuff)
        button.pack(pady=10)

    def do_stuff(self):
        print("Doing stuff!!1")


if __name__ == "__main__":
    app = MainApp()
    app.mainloop()

You can read more about TTk: Styles in the official Tk docs.

like image 20
Stephanie Burns Avatar answered Dec 13 '25 11:12

Stephanie Burns



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!