通过网格位置调用Tkinter元素

问题描述 投票:0回答:1
我正在开发一个界面,需要我突出显示与单独面板中的巴特输入相对应的网格中的标签,为此我希望使用一个由 0 和 1 的矩阵组成的“地图”,与我的网格匹配程序,然后使用该地图来更改地图中相应标签的颜色。为此,我必须能够调用标签,而不是通过其名称,而是通过其配置函数的网格位置,有没有办法做到这一点。

预先感谢您考虑我的问题。

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] 不是真正的功能,我正在寻找具有相同功能的东西。

python tkinter grid
1个回答
0
投票
听起来像家庭作业? 巧合的是,一位朋友的儿子向我提出了这个问题。我们最终得到了一个面向对象的解决方案。

因此,根据您提供的代码,可能不是您问题的答案,但也许它有帮助。

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()
    
© www.soinside.com 2019 - 2024. All rights reserved.