带最高分功能的方块拼图Python程序运行无输出(退出码0)求助
问题描述
开发一款带有最高分功能的简易方块拼图游戏,编写完代码后无法正常运行。程序执行后无任何界面显示,终端仅显示启动命令,最终以退出码0结束。
终端输出
PS C:\Users\xxx> & C:/Python311/python.exe c:/Users/xxx/Desktop/xxx.py
原始代码
import tkinter as tk import random import os import time window = tk.Tk() window.geometry("500x500") window.title("Parça Parça") author_label = tk.Label(window, text="xxx", font=("Arial", 10)) author_label.pack(side="bottom", pady=10) title_label = tk.Label(window, text="Parça Parça", font=("Arial", 20, "bold")) title_label.pack(side="top", pady=10) name_label = tk.Label(window, text="Adınızı girin:") name_label.pack() name_entry = tk.Entry(window) name_entry.pack() load_button = tk.Button(window, text="Resim Yükle") load_button.pack() def select_image(): file_path = tk.filedialog.askopenfilename() if file_path: image = image.open(file_path) image = image.resize((400, 400)) image_list = [] for i in range(0, 400, 100): for j in range(0, 400, 100): piece = image.crop((i, j, i+100, j+100)) image_list.append(piece) random.shuffle(image_list) grid = [image_list[i:i+4] for i in range(0, len(image_list), 4)] node_grid = [] for i in range(4): row = [] for j in range(4): piece = grid[i][j] node = Node(piece, i, j) row.append(node) node_grid.append(row) game_start(node_grid) load_button.config(command=select_image) class Node: def __init__(self, piece, row, col): self.piece = piece self.row = row self.col = col self.button = None self.next = None self.prev = None def create_linked_list(grid): head = None for i in range(len(grid)): for j in range(len(grid)): node = grid[i][j] if not head: head = node else: curr = head while curr.next: curr = curr.next curr.next = node node.prev = curr return head def shuffle_pieces(): global puzzle_pieces random.shuffle(puzzle_pieces) for row in range(4): for col in range(4): button = puzzle_pieces[row * 4 + col][0] button.grid(row=row+1, column=col) def move_piece(button): global moves, score empty_row, empty_col = find_empty_position() button_row, button_col = get_position(button) if empty_row == button_row and abs(empty_col - button_col) == 1 or \ empty_col == button_col and abs(empty_row - button_row) == 1: swap_buttons(button, empty_row, empty_col, button_row, button_col) moves += 1 score += 5 score_label.config(text="Score: " + str(score)) check_solution() def check_pieces(): global correct_pieces correct_pieces = 0 for piece in pieces: if piece.current_row == piece.final_row and piece.current_col == piece.final_col: correct_pieces += 1 if correct_pieces == num_pieces: messagebox.showinfo("Congratulations", "You have completed the puzzle!") score = 0 def update_score(correct_move): global score if correct_move: score += 5 else: score -= 10 score_label.config(text=f"Score: {score}") # with open('enyuksekskor.txt', 'a') as f: # f.write(f"{kullanici_adi}: Hamle sayisi: {hamle_sayisi}, Puan: {puan}\n") # def en_yuksek_skorlari_goster(): # skorlar = [] # with open('enyuksekskor.txt', 'r') as f: # for line in f: # skorlar.append(line.strip()) # # skorları puanlarına göre sırala # skorlar.sort(key=lambda x: int(x.split(':')[-1].strip().split()[-1]), reverse=True) # # en yüksek 10 skoru göster # skorlar = skorlar[:10] # skor_text = "\n".join(skorlar) # skor_label.config(text=skor_text)
问题分析与修复方案
1. 缺少Tkinter主循环
Tkinter程序必须调用window.mainloop()才能启动界面事件循环,否则程序会直接退出。在代码末尾添加:
window.mainloop()
2. 未导入必要模块
- 使用
tk.filedialog和messagebox需要导入对应子模块 - 图片处理依赖PIL库的
Image与ImageTk模块,需先通过pip install pillow安装库,再添加导入语句:
from tkinter import filedialog, messagebox from PIL import Image, ImageTk
3. 变量命名冲突
select_image函数中变量名image与导入的Image模块冲突,修改为:
img = Image.open(file_path) img = img.resize((400, 400))
后续代码中所有image引用同步替换为img。
4. 补充未定义的核心函数与变量
代码中多个核心函数和全局变量未定义,需补充:
- 初始化全局变量:
moves = 0 score_label = tk.Label(window, text="Score: 0", font=("Arial", 12)) score_label.pack(pady=5) pieces = [] num_pieces = 16
- 补充核心函数基础实现:
def game_start(node_grid): global pieces pieces = [node for row in node_grid for node in row] # 生成拼图按钮并显示 for node in pieces: tk_img = ImageTk.PhotoImage(node.piece) node.button = tk.Button(window, image=tk_img, command=lambda b=node.button: move_piece(b)) node.button.image = tk_img # 保留引用防止图片被垃圾回收 node.button.grid(row=node.row+2, column=node.col, padx=2, pady=2) # 设置空白块 empty_node = pieces[-1] empty_node.button.config(image='') empty_node.is_empty = True def find_empty_position(): for node in pieces: if hasattr(node, 'is_empty') and node.is_empty: return node.row, node.col return 3, 3 def get_position(button): for node in pieces: if node.button == button: return node.row, node.col return -1, -1 def swap_buttons(button, empty_row, empty_col, button_row, button_col): for node in pieces: if node.button == button: # 交换按钮位置 node.button.grid(row=empty_row+2, column=empty_col) node.row, node.col = empty_row, empty_col # 找到空白节点并交换位置 empty_node = next(n for n in pieces if n.row == empty_row and n.col == empty_col) empty_node.button.grid(row=button_row+2, column=button_col) empty_node.row, empty_node.col = button_row, button_col break def check_solution(): check_pieces()
5. 修复最高分功能
取消注释最高分相关代码,补充变量定义与逻辑:
def save_score(): kullanici_adi = name_entry.get().strip() or "匿名用户" with open('enyuksekskor.txt', 'a', encoding='utf-8') as f: f.write(f"{kullanici_adi}: Hamle sayisi: {moves}, Puan: {score}\n") show_high_scores() def show_high_scores(): skorlar = [] if os.path.exists('enyuksekskor.txt'): with open('enyuksekskor.txt', 'r', encoding='utf-8') as f: for line in f: skorlar.append(line.strip()) # 按分数降序排序 skorlar.sort(key=lambda x: int(x.split('Puan: ')[-1]), reverse=True) skorlar = skorlar[:10] skor_text = "\n".join(skorlar) if skorlar else "暂无最高分记录" skor_label.config(text=skor_text) # 添加最高分显示标签 skor_label = tk.Label(window, text="", font=("Arial", 10)) skor_label.pack(side="bottom", pady=5) # 修改check_pieces函数,完成时保存分数 def check_pieces(): global correct_pieces correct_pieces = 0 for piece in pieces: if piece.row == piece.final_row and piece.col == piece.final_col: correct_pieces += 1 if correct_pieces == num_pieces: messagebox.showinfo("Tebrikler!", "Puzzle'i tamamladınız!") save_score()
同时在Node类中添加原始位置记录属性:
class Node: def __init__(self, piece, row, col): self.piece = piece self.row = row self.col = col self.final_row = row # 记录原始位置 self.final_col = col self.button = None self.next = None self.prev = None self.is_empty = False
内容的提问来源于stack exchange,提问作者Batuğ Can Akpınar
相关产品推荐
相关产品推荐

