Search code examples
pythontkinter

Python Tkinter: Change button position based on window size


This is just a concept that I haven't actually programmed yet. I'm still learning the logic for Tkinter and I'm wondering how to Change button position based on the window size. The best thing I can compare my idea in my head is something similar to word wrap.

Original size:

-------------------------------
|  -----    -----    -----    |
| |     |  |     |  |     |   |
| |     |  |     |  |     |   |
|  -----    -----    -----    |
|  -----    -----             |
| |     |  |     |            |
| |     |  |     |            |
|  -----    -----             |
-------------------------------

Change Example 1:

--------------------
|  -----    -----  |
| |     |  |     | |
| |     |  |     | |
|  -----    -----  |
|  -----    -----  |
| |     |  |     | |
| |     |  |     | |
|  -----    -----  |
|  -----           |
| |     |          |
| |     |          |
|  -----           |
--------------------

Change Example 2:

-----------------------------------------------
|  -----    -----    -----    -----    -----  |
| |     |  |     |  |     |  |     |  |     | |
| |     |  |     |  |     |  |     |  |     | |
|  -----    -----    -----    -----    -----  |
-----------------------------------------------

Is there a way to do something like this?


Solution

  • You can put those buttons inside a Text widget with wrap enabled.

    Below is a simple example:

    import tkinter as tk
    
    root = tk.Tk()
    
    box = tk.Text(root, wrap="char")
    box.pack(fill="both", expand=True)
    
    for i in range(5):
        btn = tk.Button(box, text=f"Button {i+1}", width=10, height=5)
        box.window_create("end", window=btn, pady=5, padx=5)
    
    root.mainloop()
    

    enter image description here

    enter image description here

    enter image description here