【问题标题】:Colours of Buttons TkinterTkinter 按钮的颜色
【发布时间】:2018-06-10 00:55:22
【问题描述】:

所以我被要求为我的 A-Level 评估创建一个数独模拟器,并在 Tkinter 中使用 GUI。 我设法创建了一个 9x9 的按钮网格,但是我希望每 3 行都是粗体(A),或者让每组 3x3 的按钮组具有不同的颜色(B)。下面是我想到的图片。

B A

这是我的代码。

from tkinter import *

#Create & Configure root 
root = Tk()
Grid.rowconfigure(root, 0, weight=1)
Grid.columnconfigure(root, 0, weight=1)
root.resizable(width=False, height=False)

#Create & Configure frame 
frame=Frame(root, width=900, height = 900)
frame.grid(row=0, column=0, sticky=N+S+E+W)


#Create a 9x9 (rows x columns) grid of buttons inside the frame
for row_index in range(9):
    Grid.rowconfigure(frame, row_index, weight=1)
    for col_index in range(9):
        Grid.columnconfigure(frame, col_index, weight=1)
        btn = Button(frame, width = 12, height = 6) #create a button inside frame 
        btn.grid(row=row_index, column=col_index, sticky=N+S+E+W)


root.mainloop()

任何帮助将不胜感激!

请注意:我稍后打算为每个按钮添加数字,并使其可以玩数独游戏,因此在创建解决方案时请记住这一点。任何关于如何有效地为每个按钮分配一个数字的帮助(例如在 for 循环中)也将不胜感激!

【问题讨论】:

  • 我觉得这是一个很好的使用OOP的项目,每个9x9都可以认为是一个box类。
  • 关于如何将其调整为 OOP 的任何想法。我对一般编程很陌生
  • 我会看到 this post 关于 oop 结构。
  • “任何帮助”有点过于宽泛,不适合 stackoverflow 上的问题类型。

标签: python tkinter


【解决方案1】:

这是一个 MCVE,它演示了为按钮着色的方法:

import tkinter as tk

root = tk.Tk()

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}):
            colour = 'black'
        else:
            colour = None
        button = tk.Button(root, width=1, height=1, bg=colour)
        button.grid(row=row_index, column=col_index, sticky='nswe')

root.mainloop()

...当涉及到分配数字时,我会让你自己想出一个系统。

【讨论】:

  • 谢谢!我已设法将其合并到我的代码中。非常感谢您的帮助。
猜你喜欢
  • 2020-04-21
  • 2020-11-14
  • 2017-12-19
  • 2014-02-22
  • 1970-01-01
  • 2016-11-07
  • 1970-01-01
  • 2018-05-17
  • 2019-05-29
相关资源
最近更新 更多