How to get rid of widget border in Tkinter?
When designing a Tkinter application, you might want to get rid of the widget border. This is particularly applicable when creating a windowless application or when you want to place invisible buttons on an image. In this guide, we will take you through the process of removing the border of a widget in Tkinter.
To get rid of the widget border, you will need to use the overrideredirect() method.
import tkinter as tk
root = tk.Tk()
root.overrideredirect(True)
# Your code here
root.mainloop()
The overrideredirect() method is used to remove the top-level window manager’s title bar and border. When the argument of overrideredirect() is set to True, the title bar and border is removed, and the window is left with only its contents.
However, setting overrideredirect() to True has a couple of consequences. First, you will lose the ability to move your window around the desktop using the title bar. You will also not be able to resize it. Secondly, it will be impossible to close the window using the standard window manager buttons.
Nevertheless, there is a workaround to these issues. To move the window, you can bind the left mouse button to the widget and drag it to the desired location. You can also include an exit button to close the app. The following code demonstrates how to create a borderless window:
import tkinter as tk
def move_window(event):
root.geometry('+{0}+{1}'.format(event.x_root, event.y_root))
def close_app():
root.destroy()
root = tk.Tk()
root.overrideredirect(True)
root.geometry('300x200')
frame = tk.Frame(root, bg='green')
frame.pack(fill='both', expand=True)
frame.bind('<ButtonPress-1>', move_window)
frame.bind('<ButtonRelease-1>', move_window)
button = tk.Button(frame, text='Exit', command=close_app, bg='red')
button.pack(side='right')
root.mainloop()
In line 4-5, we define the move_window() method for the left mouse button click. This method sets the window position to the mouse cursor’s location. We then attach this method to the
In line 7, we define the close_app() method. This method destroys the root widget. We attach the method to a button that we packed on the frame.
We create a frame in lines 9-10 and pack it from lines 11-12. We also bind the left mouse button release event to the frame to call the move_window() method.
Finally, we add an exit button to the right side of the frame. You can customize the frame’s appearance to fit your design.
Conclusion
Getting rid of the widget border is a useful technique to create a custom Tkinter app. We have seen how to do this using the overrideredirect() method and the steps to mitigate the side effects of removing the window manager’s title bar and border. We hope this guide has been helpful.