1
I know that this code has a lot of repetition and I intend to "dry" it later. For now, I want to understand how to change the position of the buttons in Tkinter dynamically. The solution I initially thought was to use grid
to position the buttons, using variables in the arguments row
and column
, and then create a function that changes the value of these variables. However, this "solution" is not working. Follow code below for replication of the problem:
import tkinter as tk
from tkinter import ttk
import random
def change_position():
new_row = button_6.grid_info().get("row")
new_col = button_6.grid_info().get("column")
button_6.grid(row=button_empty.grid_info().get("row"), column=button_empty.grid_info().get("column"))
button_empty.grid(row=new_row, column=new_col)
class Single_window(tk.Tk):
def __init__(self):
super().__init__()
self.title('5-Sliding Block')
self.resizable(False, False)
root = Single_window()
button_f1 = tk.Frame(root)
button_4 = ttk.Button(button_f1, text = '4')
button_4.grid(row=0, column=0)
button_5 = ttk.Button(button_f1, text = '5')
button_5.grid(row=0, column=1)
button_6 = ttk.Button(button_f1, text = '6', command = change_position)
button_6.grid(row= 0, column= 2)
button_f1.pack(side = 'top')
button_f2 = tk.Frame(root)
button_7 = ttk.Button(button_f2, text = '7')
button_7.grid(row=1, column=0)
button_8 = ttk.Button(button_f2, text = '8')
button_8.grid(row=1, column=1)
button_empty = ttk.Button(button_f2)
button_empty.grid(row=1, column=2)
button_f2.pack(side = 'top')
root.mainloop()
My goal is to create a game of "Sliding Blocks" of order 6. See example in this website.