You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter猜拳游戏按钮绑定多函数报错及修复求助

石头剪刀布游戏绑定Delete函数后报错修复方案

问题描述

我开发的石头剪刀布游戏有Paper、Rock、Scissors三个按钮,原本仅绑定Game()函数,新增Delete()函数用于删除重复显示的标签后,绑定该函数出现了无法理解的错误。

错误信息

File "c:\Users\MiroP\WUA\Random.py", line 105, in <lambda>
    (ScissorsButton := Button(root, image = scissors, bg="white", bd=0, command=lambda:[Game(player_choice_string=Game), Delete()]("scissors"))).pack(pady=10)
  File "c:\Users\MiroP\WUA\Random.py", line 100, in Game
    win_lose_tie_label = Label(root, text="Your choice was: "+player_choice_string+" and the enemy's choice was: "+computer_input, font=("Verdana", 5),bg = "white", bd=0).pack()       
TypeError: can only concatenate str (not "function") to str

错误原因分析

  1. 按钮command参数写法错误:你用了lambda:[Game(), Delete()]("rock")这种错误语法,调用Game时还把Game函数本身当成参数传入,导致player_choice_string是函数对象而非字符串,文本拼接时触发类型错误。
  2. Delete函数逻辑错误:尝试销毁整数类型的user_points,不符合Tkinter组件销毁逻辑,应该销毁的是标签组件。
  3. Label组件赋值错误:Label(...).pack()会返回None,导致points_label和win_lose_tie_label指向None,无法调用destroy()。
  4. 游戏得分逻辑错误:玩家选paper、电脑选scissors时,错误地给玩家加分,实际应该给电脑加分。

修复步骤及代码

1. 修正按钮的command绑定

把按钮的command参数改成正确的lambda写法,传递对应的字符串参数给Game函数:

(RockButton := Button(root, image=rock, bg="white", bd=0, command=lambda: [Game("rock"), Delete()])).pack(side=LEFT)
(PaperButton := Button(root, image=paper, bg="white", bd=0, command=lambda: [Game("paper"), Delete()])).pack(side=RIGHT)
(ScissorsButton := Button(root, image=scissors, bg="white", bd=0, command=lambda: [Game("scissors"), Delete()])).pack(pady=10)

2. 修正Delete函数

改成销毁标签组件,同时处理标签未创建的情况避免报错:

def Delete():
    global points_label, win_lose_tie_label
    try:
        points_label.destroy()
        win_lose_tie_label.destroy()
    except NameError:
        pass  # 标签未创建时跳过销毁操作

3. 修正Label组件赋值方式

将创建Label和pack()分开执行,确保变量指向组件对象而非None:

# 替换原来的两行代码
points_label = Label(root, text=f"You have {user_points} and the enemy now has: {computer_points}!", bg="white", bd=0)
points_label.pack()
win_lose_tie_label = Label(root, text=f"Your choice was: {player_choice_string} and the enemy's choice was: {computer_input}", font=("Verdana", 5), bg="white", bd=0)
win_lose_tie_label.pack()

4. 修正得分逻辑错误

在Game函数中,玩家选paper、电脑选scissors的分支,把user_points += 1改成computer_points += 1:

elif player_choice_string == "paper":
    # ... 其他分支不变
    elif computer_input == "scissors":
        print("Your input is paper")
        print("Computer input is scissors")
        print("you lost!")
        computer_points += 1  # 这里修正为电脑加分

修复后的完整代码

#Import List
from tkinter import *
from random import randint
from tkinter import font
from tkinter.tix import COLUMN
from turtle import color
from tkinter import ttk
import random
from PIL import ImageTk,Image
#Basics
root = Tk()
root.title("Rock Paper Scissors -Made by Trapgrave")
root.iconbitmap("c:/images/star.ico")
root.config(bg="white")

#Images
rock = PhotoImage(file="c:/images/rock.png")
paper = PhotoImage(file="c:/images/paper.png")
scissors = PhotoImage(file="c:/images/scissors.png")
#-
Choose = Label(root, font=("Roboto", 15), text = "Rock, Paper, Scissors!", bg="white").pack(side = TOP)

#Storing points
user_points = 0
computer_points = 0
#Options

def Delete():
    global points_label, win_lose_tie_label
    try:
        points_label.destroy()
        win_lose_tie_label.destroy()
    except NameError:
        pass

def Game(player_choice_string):
    print("player chose: {}".format(player_choice_string))

    global user_points, computer_points

    options = ["rock", "paper", "scissors"]
    computer_input = random.choice(options)

    if player_choice_string == "rock":
        if computer_input == "rock":
            print("Your input is rock")
            print("Computer input is rock")
            print("It is a tie!")
        elif computer_input == "paper":
            print("Your input is rock")
            print("Computer input is paper")
            print("you lost!")
            computer_points += 1
        elif computer_input == "scissors":
            print("Your input is rock")
            print("Computer input is scissors")
            print("you win!")
            user_points += 1

    elif player_choice_string == "paper":
        if computer_input == "rock":
            print("Your input is paper")
            print("Computer input is rock")
            print("You win!")
            user_points += 1
        elif computer_input == "paper":
            print("Your input is paper")
            print("Computer input is paper")
            print("It is a tie!")
        elif computer_input == "scissors":
            print("Your input is paper")
            print("Computer input is scissors")
            print("you lost!")
            computer_points += 1  # 修正得分逻辑

    elif player_choice_string == "scissors":
        if computer_input == "rock":
            print("Your input is scissors")
            print("Computer input is rock")
            print("You lost!")
            computer_points += 1
        elif computer_input == "paper":
            print("Your input is scissors")
            print("Computer input is paper")
            print("You win!")
            user_points += 1
        elif computer_input == "scissors":
            print("Your input is scissors")
            print("Computer input is scissors")
            print("It is a tie!")   
    global points_label
    global win_lose_tie_label
    # 修正Label赋值方式
    points_label = Label(root, text=f"You have {user_points} and the enemy now has: {computer_points}!", bg="white", bd=0)
    points_label.pack()
    win_lose_tie_label = Label(root, text=f"Your choice was: {player_choice_string} and the enemy's choice was: {computer_input}", font=("Verdana", 5), bg="white", bd=0)
    win_lose_tie_label.pack()

# 修正按钮command绑定
(RockButton := Button(root, image=rock, bg="white", bd=0, command=lambda: [Game("rock"), Delete()])).pack(side=LEFT)
(PaperButton := Button(root, image=paper, bg="white", bd=0, command=lambda: [Game("paper"), Delete()])).pack(side=RIGHT)
(ScissorsButton := Button(root, image=scissors, bg="white", bd=0, command=lambda: [Game("scissors"), Delete()])).pack(pady=10)

root.geometry("500x500")
root.mainloop()

内容的提问来源于stack exchange,提问作者trapgrave

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 10:40:25