【问题标题】:Corresponding arrays with buttons带有按钮的对应数组
【发布时间】:2018-01-15 23:50:38
【问题描述】:

我正在制作一个数独网格,并且我已经成功地生成了一个 9x9 的按钮网格。 我还创建了一个包含 81 个值的数组。 无论如何,我可以获取按钮内的值以匹配它们在数组中的相关索引。我只想显示几个数字,也许每行大约 3 个?有什么想法!?

这是按钮生成器:

#Create a 9x9 (rows x columns) grid of buttons inside the frame
for row_index in range(9):
    for col_index in range(9):
        if (row_index in {0, 1, 2, 6, 7, 8} and col_index in {3, 4, 5}) or \
                (row_index in {3, 4, 5} and col_index in {0, 1, 2, 6, 7, 8}): #Colours a group of 3x3 buttons together to differentiate the board better.
            colour = 'gray85'
        else:
            colour = 'snow'
        c=True
        btn = Button(frame, width = 12, height = 6, bg=colour) #create a button inside frame 
        btn.grid(row=row_index, column=col_index, sticky=N+S+E+W)
        btn.bind("<Button-1>", LeftClick)
        buttons.append(btn)

这是值数组:

    easy = [
 [8,5,1,9,4,3,6,7,2],
 [4,3,9,6,7,2,5,1,8],
 [6,7,2,1,8,5,9,3,4],
 [1,2,3,7,9,4,8,6,5],
 [7,6,5,2,1,8,4,9,3],
 [9,4,8,3,5,6,7,2,1],
 [5,9,6,4,2,1,3,8,7],
 [2,8,7,5,3,9,1,4,6],
 [3,1,4,8,6,7,2,5,9],
]

我玩过枚举的想法,但没有成功。

def Enumerate():
    for row_index in enumerate(easy):
        for col_index in enumerate(row_index):
            for btn in buttons:
                btn.config(text=col_index)

当我运行枚举函数时,会显示以下内容。 https://gyazo.com/1aeba588e321b5228e2d50d68ab24583

对于每个按钮的文本,它会输出数组中的最终列表。我觉得这与枚举周围的循环有关,但是我不确定我可以执行此任务的任何其他方式。

【问题讨论】:

    标签: python arrays button tkinter sudoku


    【解决方案1】:

    在创建时将文本分配给按钮有意义吗?例如,

    button_text = str(easy[row_index][col_index])
    btn = Button(frame, width = 12, height = 6, bg=colour, text=button_text)
    

    【讨论】:

    • 这是可行的。但是我打算增加难度级别。我怎么能做到这一点,以根据所选难度级别的变化(请记住,难度级别是在顶部的菜单栏上选择的,因此,当轻松张紧我希望这些数字生成时)
    • 大概你会有其他嵌套列表,例如 hard,其中包含不同的数据。只需编写一个使用与创建按钮时类似的范围 for 循环的函数,使用不同的列表获取按钮文本,这次只需配置按钮文本button.configure(text=&lt;new text&gt;)
    • 我不能使用 button.configure。它在按钮生成器循环之外无法识别。我以前有过这个问题。有什么建议吗?
    • 您将按钮定义为列表,我从buttons.append(btn) 看到。您必须使按钮成为全局变量或类变量。如果是一个类变量,那么同一个类中的所有方法都可以访问 self.buttons。如果将其设为全局,只需在使用它的函数顶部使用 global buttons 语句即可。
    【解决方案2】:

    您的 Enumerate() 函数有问题:

    1. enumerate 在每次迭代时返回一个元组。该元组由 iterable(list) 中的索引和该索引处的列表项组成。这意味着您的第二个 for 语句不是遍历列表中的每一行数据,而是遍历 (index, list) 的元组。
    2. 您通过 col_index 循环遍历并处理每次迭代的整个按钮列表。

    试试这个功能:

    def populate():
        for row_index, row_data in enumerate(easy):
            for col_index, cell_value in enumerate(row_data):
                buttons[(row_index * 9) + col_index].config(text=cell_value)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-02
      • 1970-01-01
      • 2017-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 2017-08-06
      相关资源
      最近更新 更多