简体   繁体   中英

tkinter Python: How to change Button colour after clicking other button?

I want the color of neighbouring buttons to change when I click a button. I am making a GUI in tkinter for a 19x19 boardgame. Imagine something like mindsweeper, so the entire board consists of Buttons. I am using python 3.7

Here is my code for a simple 1x2 playing field.

import tkinter as tk

def do_something(p):
    p.configure(bg = 'blue')

def personal_do_something(p):
    p.configure(bg = 'blue')
    p1.configure(bg = 'blue')

window = tk.Tk()
frame = tk.Frame(master = window)
frame.pack()
p1 = tk.Button(master = frame, width = 10, height = 5, bg = 'orange', command = lambda:do_something(p1))
p2 = tk.Button(master = frame, width = 10, height = 5, bg = 'khaki', command = lambda:personal_do_something(p2))
p1.pack(side=tk.LEFT)
p2.pack(side=tk.LEFT)
window.mainloop()

starting situation:

开始

click p1:

p1 点击

click p2:

p2 点击

When p1 is clicked, only p1 turns blue, but not its neighbour p2. when p2 is clicked both p1 and p2 turn blue. This however only works because p2 has a personal_do_something() function. In this function I explicitly tell p1 to turn blue. This might be a viable method for a small 1x2 board, but I can't write personal functions for every button when there are 19x19 buttons. Does anyone have any clue how I could write 1 general function that always turns the direct neighbours blue? I assume I would have to add some kind of attribute to a button, for example a coordinate, and then search all the buttons that match neighbouring coordinates or something like that. But I have no clue how.

Thanks in advance:)

You can store the references of those buttons in a 2D list and pass the row and col of the clicked button to do_something() function. Then you can update the background color of those buttons based on passed row and col .

Below is an example based on your code:

import tkinter as tk

def do_something(row, col):
    buttons[row][col].config(bg="blue")
    # change direct connected buttons (left, right, up, down)
    for dir in (-1, +1):
        if 0 <= row+dir < len(buttons):
            buttons[row+dir][col].config(bg="blue")
        if 0 <= col+dir < len(buttons[row]):
            buttons[row][col+dir].config(bg="blue")

window = tk.Tk()
frame = tk.Frame(window)
frame.pack()

ROWS = 10
COLS = 10

buttons = [[None]*COLS for _ in range(ROWS)] # for storing references of buttons
for row in range(ROWS):
    for col in range(COLS):
        buttons[row][col] = tk.Button(frame, width=10, height=5, bg="orange", command=lambda r=row,c=col: do_something(r,c))
        buttons[row][col].grid(row=row, column=col, sticky="nsew")

window.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM