I have a quite complex GUI and would like to obtain sizeable tkinter widgets that have a fixed absolute position with respect to the window edges instead of a fixed relative width and height. Since the GUI contains many widgets I do not want to use pack but place.
The following code produces a button with an absolute position with respect to the top and the left window edge. Upon resizing the window, the margin between the button and the right and bottom window edge changes, but I want to have it fixed by something like place(left=50, top=50, right=50, bottom=50)
.
import tkinter as tk
class App():
def __init__(self):
self.root = tk.Tk()
self.root.geometry("400x400 200 100")
self.button = tk.Button(self.root, text='Button')
self.button.place(x=50, y=50, relwidth=0.8, relheight=0.8, anchor='nw')
self.root.mainloop()
if __name__ == "__main__":
app = App()
CodePudding user response:
You can combine relative absolute widths and heights. For example, if you set relwidth
to 1.0 and width
to -100, you will get the desired effect.
The reason for -100 instead of -50 is that the widget starts at an x coordinate of 50. You then set the initial width to 100% of the width of the parent (in this case, 400), meaning the right edge will be at 450. We want the right edge to be at 350, so we need to subtract 100.
self.button.place(x=50, y=50, relwidth=1, relheight=1, width=-100, height=-100)