用python写一个国际象棋棋盘的代码
时间: 2023-12-17 07:57:23 浏览: 225
这是一个使用Python和tkinter库编写的国际象棋棋盘代码:
```python
import tkinter as tk
class ChessBoard(tk.Frame):
def __init__(self, parent, rows=8, columns=8, size=64, color1="white", color2="gray"):
tk.Frame.__init__(self, parent)
self.rows = rows
self.columns = columns
self.size = size
self.color1 = color1
self.color2 = color2
self.widgets = []
self.grid()
self.create_widgets()
def create_widgets(self):
for row in range(self.rows):
for col in range(self.columns):
x1 = col * self.size
y1 = row * self.size
x2 = x1 + self.size
y2 = y1 + self.size
color = self.color1 if (row + col) % 2 == 0 else self.color2
widget = tk.Canvas(self, width=self.size, height=self.size, bg=color, highlightthickness=0)
widget.grid(row=row, column=col)
self.widgets.append(widget)
if __name__ == "__main__":
root = tk.Tk()
root.title("Chess Board")
cb = ChessBoard(root)
cb.pack(side="top", fill="both", expand=True)
root.mainloop()
```
这个代码会创建一个8x8的棋盘,每个格子的大小为64像素,使用两种颜色交替,形成黑白相间的棋盘。你可以根据需要修改行数、列数、格子大小、颜色等参数。你也可以在每个格子上添加棋子或者其他元素。
阅读全文