Advertisement
here2share

# tk_4x4_ButtonLayout_demo.py

Jan 19th, 2024
1,100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.33 KB | None | 0 0
  1. # tk_4x4_ButtonLayout_demo.py
  2.  
  3. import tkinter as tk
  4.  
  5. def on_enter(event):
  6.     event.widget.config(bg="red")
  7.     event.widget.config(fg="white")
  8.  
  9. def on_leave(event):
  10.     widget = event.widget
  11.     if button_colors[widget] == 'green':
  12.         widget.config(bg="green")
  13.         widget.config(fg="white")
  14.     else:
  15.         widget.config(bg="yellow")
  16.         widget.config(fg="gray")
  17.  
  18. def on_click(event):
  19.     widget = event.widget
  20.     if button_colors[widget] == 'green':
  21.         widget.config(bg="yellow")
  22.         widget.config(fg="gray")
  23.         button_colors[widget] = 'yellow'
  24.     else:
  25.         widget.config(bg="green")
  26.         widget.config(fg="white")
  27.         button_colors[widget] = 'green'
  28.  
  29. root = tk.Tk()
  30. root.geometry("400x400+10+10")
  31. root.title("# tk_4x4_ButtonLayout_demo.py")
  32.  
  33. button_colors = {}  # Dictionary to store button colors
  34.  
  35. for i in range(4):
  36.     root.grid_rowconfigure(i, weight=1)
  37.     root.grid_columnconfigure(i, weight=1)
  38.     for j in range(4):
  39.         button = tk.Button(root, text=f"{i*4+j+1}", font=("Arial", 50), fg="gray", bg="yellow")
  40.         button.grid(row=i, column=j, sticky="nsew")
  41.         button.bind("<Enter>", on_enter)
  42.         button.bind("<Leave>", on_leave)
  43.         button.bind("<Button-1>", on_click)
  44.         button_colors[button] = 'yellow'  # Initial color
  45.  
  46. root.mainloop()
  47.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement