用python中的tkinter模块编译一个主窗体含有登录和退出键。点击登录可以进入另一个窗体,在另一个窗体中可以玩五子棋。点击退出直接退出。
时间: 2024-05-12 12:18:46 浏览: 52
以下是一个简单的五子棋小游戏,包含登录和退出按钮。
```python
import tkinter as tk
import tkinter.messagebox as msgbox
class MainWindow:
def __init__(self, master):
self.master = master
master.title("五子棋小游戏")
# 创建登录和退出按钮
self.login_button = tk.Button(master, text="登录", command=self.login)
self.login_button.pack(side="left", padx=10, pady=10)
self.quit_button = tk.Button(master, text="退出", command=self.quit)
self.quit_button.pack(side="left", padx=10, pady=10)
def login(self):
# 进入另一个窗体
login_window = tk.Toplevel(self.master)
login_window.title("登录")
# 创建用户名和密码输入框
tk.Label(login_window, text="用户名:").grid(row=0, column=0)
self.username_entry = tk.Entry(login_window)
self.username_entry.grid(row=0, column=1)
tk.Label(login_window, text="密码:").grid(row=1, column=0)
self.password_entry = tk.Entry(login_window, show="*")
self.password_entry.grid(row=1, column=1)
# 创建登录按钮
login_button = tk.Button(login_window, text="登录", command=self.check_login)
login_button.grid(row=2, column=1, pady=10)
def check_login(self):
# 检查用户名和密码是否正确
username = self.username_entry.get()
password = self.password_entry.get()
if username == "admin" and password == "123456":
# 登录成功,进入游戏窗口
self.game_window = tk.Toplevel(self.master)
self.game_window.title("五子棋")
self.game = Game(self.game_window)
else:
# 登录失败,弹出提示框
msgbox.showerror("错误", "用户名或密码错误")
def quit(self):
# 退出程序
self.master.quit()
class Game:
def __init__(self, master):
self.master = master
self.turn = "black"
self.board = [[None for _ in range(15)] for _ in range(15)]
# 创建棋盘
self.canvas = tk.Canvas(master, width=450, height=450, bg="#F0D9B5")
self.canvas.pack()
for i in range(15):
self.canvas.create_line(30, 30 + i*30, 420, 30 + i*30)
self.canvas.create_line(30 + i*30, 30, 30 + i*30, 420)
# 创建落子事件
self.canvas.bind("<Button-1>", self.drop_piece)
def drop_piece(self, event):
x, y = event.x, event.y
row, col = (y - 30) // 30, (x - 30) // 30
if self.board[row][col] is None:
if self.turn == "black":
self.canvas.create_oval(30 + col*30 - 13, 30 + row*30 - 13, 30 + col*30 + 13, 30 + row*30 + 13, fill="black")
self.board[row][col] = "black"
self.turn = "white"
else:
self.canvas.create_oval(30 + col*30 - 13, 30 + row*30 - 13, 30 + col*30 + 13, 30 + row*30 + 13, fill="white")
self.board[row][col] = "white"
self.turn = "black"
if self.check_win(row, col):
winner = "黑方" if self.turn == "white" else "白方"
msgbox.showinfo("游戏结束", f"{winner}获胜!")
self.master.destroy()
def check_win(self, row, col):
# 判断是否五子连珠
def count(dx, dy):
cnt = 0
while 0 <= row+dx <= 14 and 0 <= col+dy <= 14 and self.board[row+dx][col+dy] == self.board[row][col]:
cnt += 1
dx, dy = dx+dx, dy+dy
return cnt
if count(1, 0) + count(-1, 0) >= 4: return True
if count(0, 1) + count(0, -1) >= 4: return True
if count(1, 1) + count(-1, -1) >= 4: return True
if count(1, -1) + count(-1, 1) >= 4: return True
return False
root = tk.Tk()
app = MainWindow(root)
root.mainloop()
```
阅读全文