Python Forum
[Tkinter] TKinter Remove Button Frame
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] TKinter Remove Button Frame
#1
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()

Attached Files

Thumbnail(s)
   
Reply
#2
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!
Reply
#3
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.
Reply
#4
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()

Attached Files

Thumbnail(s)
   
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#5
Edited image using gimp
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#6
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.
Reply
#7
(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.
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#8
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.
Reply
#9
(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.
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  tkinter - touchscreen, push the button like click the mouse John64 5 1,604 Jan-06-2024, 03:45 PM
Last Post: deanhystad
  [Tkinter] Help running a loop inside a tkinter frame Konstantin23 3 2,349 Aug-10-2023, 11:41 AM
Last Post: Konstantin23
  tkinter mapview in a frame janeik 2 1,903 Jun-22-2023, 02:53 PM
Last Post: deanhystad
  Centering and adding a push button to a grid window, TKinter Edward_ 15 8,910 May-25-2023, 07:37 PM
Last Post: deanhystad
  Can't get tkinter button to change color based on changes in data dford 4 4,164 Feb-13-2022, 01:57 PM
Last Post: dford
  Creating a function interrupt button tkinter AnotherSam 2 6,327 Oct-07-2021, 02:56 PM
Last Post: AnotherSam
  [Tkinter] Have tkinter button toggle on and off a continuously running function AnotherSam 5 6,002 Oct-01-2021, 05:00 PM
Last Post: Yoriz
  [Tkinter] Trouble changing Font within tkinter frame title AnotherSam 1 5,160 Sep-30-2021, 05:57 PM
Last Post: menator01
  tkinter showing image in button rwahdan 3 6,285 Jun-16-2021, 06:08 AM
Last Post: Yoriz
  tkinter frame camera opencv Nick_tkinter 9 6,496 Mar-21-2021, 06:41 PM
Last Post: Nick_tkinter

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020