预先感谢您考虑我的问题。
from tkinter import *
root = Tk()
val_x = 20
val_y = 20
label_tl = Label(root, text="1", padx=val_x, pady=val_y)
label_tr = Label(root, text="2", padx=val_x, pady=val_y)
label_bl = Label(root, text="3", padx=val_x, pady=val_y)
label_br = Label(root, text="4", padx=val_x, pady=val_y)
label_tl.grid(row=0, column=0)
label_tr.grid(row=0, column=1)
label_bl.grid(row=1, column=0)
label_br.grid(row=1, column=1)
map_one = [[0, 0], [1, 0]]
for x in map_one:
for y in x:
if y == 0:
grid[x, y].config(bg="white")
else
grid[x,y].config(bg="blue")
root.mainloop()
这是我想要的代码,尽管 grid[x, y] 不是真正的功能,我正在寻找具有相同功能的东西。
因此,根据您提供的代码,可能不是您问题的答案,但也许它有帮助。
import random
import tkinter as tk
from dataclasses import dataclass
class Grid:
PADX = 40
PADY = 40
COLOR_ENABLED = 'teal'
COLOR_DISABLED = 'white'
def __init__(self, tk_root, grid_size):
self.grid_size = grid_size
self.root = tk_root
self.root.configure(bg=self.COLOR_DISABLED)
self.data = []
counter = 1
for y in range(self.grid_size):
for x in range(self.grid_size):
label = tk.Label(self.root,
text=counter,
padx=self.PADX,
pady=self.PADY,
bg=self.COLOR_DISABLED)
label.grid(row=y, column=x)
self.data.append(Field(self, x=x, y=y, widget=label))
counter += 1
def set_active(self, x, y):
for field in self.data:
field.switch_active(x, y)
@dataclass
class Field:
parent: Grid
x: int
y: int
widget: tk.Label
active: bool = False
def _update_color(self):
color = self.parent.COLOR_ENABLED if self.active else self.parent.COLOR_DISABLED
self.widget.configure(bg=color)
def switch_active(self, x, y):
self.active = True if self.x == x and self.y == y else False
self._update_color()
root = tk.Tk()
grid = Grid(root, grid_size=6)
def grid_highlight_test():
"""
highlights a random label on the grid, loops forever
"""
random_x = random.randint(0, grid.grid_size - 1)
random_y = random.randint(0, grid.grid_size - 1)
grid.set_active(
x=random_x,
y=random_y
)
print(f'Coordinates X: {random_x} | Y: {random_y}')
root.after(500, grid_highlight_test)
grid_highlight_test()
root.mainloop()