按钮Tkinter的颜色

问题描述 投票:0回答:1

所以我被要求为我的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循环中)也将不胜感激!

python tkinter
1个回答
0
投票

这是一个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()

......当谈到分配号码时,我会让你想出一个系统。

© www.soinside.com 2019 - 2024. All rights reserved.