How can i move a frame with buttons in tkinter?

2k Views Asked by At

I made a button that plus the x axis with 50 if i press it.If i press the button tho it doesn't move,yes it changes the value but doesn't move. I tried a while loop but it crashed the program.

1

There are 1 best solutions below

1
patthoyts On

In general we use pack and grid geometry managers to handle widget placement in Tk. However, if you want to explicitly control the placement then you can use place which allows you to specify the location in either pixel or relative coordinates.

Here is an example of a frame with a button inside that moves when you click the button. Note that the button is positioned relative to its parent container so moves with the frame.

import tkinter as tk
import tkinter.ttk as ttk

class App(ttk.Frame):
    def __init__(self, master, **kwargs):
        super(App, self).__init__(master=master, **kwargs)
        master.wm_geometry('640x480')
        self.frame = f = tk.Frame(self, width=200, height=80, relief=tk.SUNKEN, borderwidth=2)
        b = ttk.Button(f, text="Move", command=self.move_frame)
        b.place(x=2, y=2)
        f.place(x=2, y=2)
        self.place(relheight=1.0, relwidth=1.0)

    def move_frame(self):
        x = self.frame.winfo_x()
        x = x + 10
        self.frame.place(x=x)

def main():
    root = tk.Tk()
    app = App(root)
    root.mainloop()

if __name__ == '__main__':
    main()