Python Forum
[Tkinter] TKinter Remove Button Frame - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: GUI (https://python-forum.io/forum-10.html)
+--- Thread: [Tkinter] TKinter Remove Button Frame (/thread-41436.html)



TKinter Remove Button Frame - Nu2Python - Jan-15-2024

Hi All - How can I remove the button frame in my code? I have tried a few examples I found, but have had no luck. I see one argument example for 'borderwidth=0' but does not seem to change anything. I am using a toggle button with images. Attached picture is what I have showing for my button. The image has rounded corners, so I want to remove the frame of the button completely. Thanks for any help with this.

import tkinter as tk
from tkinter import *
from tkinter import messagebox
import requests
import http.client
import time
import json
   
path = ""

SONOFF_Temp  = 'http://192.168.0.130/cm?cmnd=status+10'
sonoff_url = 'NOT_INIT'


class RelayButton(tk.Button):
    """A button that toggles a relay"""
    def __init__(self, parent, url="", on_image=None, off_image=None, **kwargs):
        super().__init__(parent, image=off_image, command=self.toggle)
        self.url = url
        self._on = False
        self.on_image = on_image
        self.off_image = off_image
        self.label = Label(text="", bg="White", fg="Black", font=("Helvetica", 12))
        self.label.place(x=10,y=15)
        self.update_clock()
        self.templabel = Label(text="temp info", bg="White", fg="Black", font=("Helvetica", 12))
        self.templabel.place(x=10, y=40)
        #self.getTemp()
        self.master.configure(background="white")
        
    @property
    def on(self):
        """Return state of the relay"""
        return self._on
   
    @on.setter
    def on(self, on):
        """Set state of the relay"""
        
        self._on = on

        try:
            if on:
                requests.post(f"{self.url}cm?cmnd=Power On")
                self["image"] = self.on_image
            else:
                requests.post(f"{self.url}cm?cmnd=Power Off")
                self["image"] = self.off_image
        except:
            messagebox.showinfo("Error")
    def toggle(self):
        """Toggle state of the relay"""
        self.on = not self.on
        
    def update_clock(self):
        now = time.strftime("%I:%M:%S %p " + ' - ' + "%x")
        self.label.configure(text='Time/Date:  ' + now)
        self.after(1000, self.update_clock)
        
    def getTemp(self):
        sonoff_url = SONOFF_Temp
        sonR1 = requests.get(sonoff_url)
        x = json.loads(sonR1.text)
        status = x["StatusSNS"]
        timestamp = status["Time"]
        device_names = list(status.keys())[1:-1]
        temp_units = status["TempUnit"]
        
        for name in device_names:
            device = status[name]
            #print(f'ID={name}, Temperature={device["Temperature"]} {temp_units}')
            self.templabel.configure(text='Living Room '+f'Temperature: {device["Temperature"]} {temp_units}')
            self.after(5000, self.getTemp)
            
   
def new_button(name, url, parent, row, column, **kwargs):
    """Convenience functon that creates a RelayButton"""
    on_image = tk.PhotoImage(file=f"{path}{name}_on.png")
    off_image = tk.PhotoImage(file=f"{path}{name}_off.png")
    button = RelayButton(parent, url, on_image, off_image, **kwargs)
    button.grid(row=row, column=column, padx=70, pady=110)
    return button


   
def main():
    app = tk.Tk()
    app.title('Home Relay Control')
    buttons = [
        #new_button('lvgRoom', "http://192.168.0.101/", app, 0, 0),
        new_button('frPorch', "http://192.168.0.130/", app, 0, 1)
        ]
    
    for b in buttons:
        b.on = False
    app.mainloop()
    
    
if __name__ == "__main__":
    main()



RE: TKinter Remove Button Frame - JamesGreenwald - Jan-15-2024

Replying for the update. Thank you so much for all the suggestions, I learned a lot of things. I am a student and I am Navigating the academic maze just got easier with CustomWriting, and here custom essay writing service is a lifesaver, offering 24/7 professional help. Trust me; you won't find a more reliable ally in your academic journey!


RE: TKinter Remove Button Frame - deanhystad - Jan-15-2024

Setting borderwidth works fine for me. A pared down version of your code using some png files I have laying around:
import tkinter as tk

class RelayButton(tk.Button):
    def __init__(self, parent, on_image, off_image):
        self.images = {True: on_image, False: off_image}
        self.on = False
        super().__init__(
            parent,
            image=off_image,
            command=self.toggle,
            borderwidth=0,
        )

    def toggle(self):
        self.on = not self.on
        self["image"] = self.images[self.on]

app = tk.Tk()
RelayButton(
    app,
    tk.PhotoImage(file="games/ttt/o.png"),
    tk.PhotoImage(file="games/ttt/x.png"),
).pack(padx=100, pady=100)
app.mainloop()
I am assuming that the frame in your picture is not part of your image. You should verify that.

The little corners of your image outside the rounded button must also be the same background color as the main window, or you'll need to use RGBA images that have transparent backgrounds. I don't know if tkinter.PhotoImage handles transparency. You might have to use PIL to load an RGBA image. I don't normally bother with transparency in tkinter because all tkinter controls (like buttons) have an opaque background.


RE: TKinter Remove Button Frame - rob101 - Jan-15-2024

Maybe this will be of help...

I've had to do a very aggressive crop on your button image in order to make this work and it's not prefect.

import tkinter as tk
from tkinter.messagebox import showinfo

colour_theme = "#D2D2D2"

# root window
root = tk.Tk()
root.geometry('400x400')
root.resizable(False, False)
root.title('Image Button Demo')
root.config(
    bg=colour_theme
)


# button
def button_clicked():
    showinfo(
        title='Information',
        message='Button clicked!'
    )


icon = tk.PhotoImage(file='.assets/frPorch_off.png')
button = tk.Button(
    root,
    image=icon,
    command=button_clicked,
    activebackground=colour_theme,
    background=colour_theme,
    borderwidth=0,
    highlightbackground=colour_theme,
    width=207,
    height=207

)

button.pack(
    ipadx=5,
    ipady=5,
    expand=True
)


root.mainloop()



RE: TKinter Remove Button Frame - menator01 - Jan-16-2024

Edited image using gimp


RE: TKinter Remove Button Frame - Nu2Python - Jan-16-2024

Thanks 'deanhystad' - I played around with this and seems to be working ok. I wish creating rounded corner buttons was easier, but when I looked into that it seems way to complicated to bother with. I am curious though about your mention of the RGBA images, I need to look into that.

rob101 - Thanks for your help as well, I need to play with this one also. Still learning a lot here with Python and Tkinter.

menator01 - thanks for the cropped image.

Appreciate all your time in helping me out.


RE: TKinter Remove Button Frame - rob101 - Jan-16-2024

(Jan-16-2024, 04:49 PM)Nu2Python Wrote: rob101 - Thanks for your help as well, I need to play with this one also. Still learning a lot here with Python and Tkinter.

You're welcome.

Tbh, I find that a GUI design app does much of the heavy lifting, allowing one to concentrate more on app functionality. I have made a few posts about that and what I use, but if you'd like me to link-up what I use, here, in your thread, then I'd be more than happy to do that.


RE: TKinter Remove Button Frame - Nu2Python - Jan-16-2024

rob101 - Thanks, that would be great actually. I am all for anything you want to share with me. There is plenty to learn for me in Python and I really enjoy the GUI stuff.


(Jan-16-2024, 04:54 PM)rob101 Wrote:
(Jan-16-2024, 04:49 PM)Nu2Python Wrote: rob101 - Thanks for your help as well, I need to play with this one also. Still learning a lot here with Python and Tkinter.

You're welcome.

Tbh, I find that a GUI design app does much of the heavy lifting, allowing one to concentrate more on app functionality. I have made a few posts about that and what I use, but if you'd like me to link-up what I use, here, in your thread, then I'd be more than happy to do that.



RE: TKinter Remove Button Frame - rob101 - Jan-16-2024

(Jan-16-2024, 05:54 PM)Nu2Python Wrote: Thanks, that would be great actually.

No worries.

Rather than reiterate what has already been said, I'll link to my post in the N&D Forum. I've also a couple of posts in the Code sharing Forum, for which I've used the PAGE GUI generator; they're easy to spot.