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

Tkinter Entry组件<Return>事件失效及电脑随机选择异常问题

石头剪刀布游戏问题解决方案

问题1:Enter键触发start_game时报错TypeError: start_game() takes 0 positional arguments but 1 was given

  • 原因:Tkinter使用bind()绑定键盘事件时,会自动把**事件对象(event)**作为参数传递给回调函数,但你的start_game()没有定义参数接收这个对象,导致参数不匹配报错。
  • 修复方法:给start_game()添加一个可选的event参数(按钮的command调用时不会传参数,所以要设为可选):
def start_game(event=None):  # 添加可选的event参数,兼容两种调用方式
    controller.set_user_name(input_name.get())
    frame.destroy()
    logo_label.destroy()
    name.destroy()
    input_name.destroy()
    sub.destroy()
    main_game_window()

这样不管是点击按钮(无参数调用)还是按Enter键(带event参数调用),函数都能正常执行。

问题2:电脑仅在初始化时随机选择一次,每轮游戏未更新选择

  • 原因:Python的默认参数值只会在函数定义时计算一次。你在Player.__init__和set_choice方法中写的choice=random.choice(choices),这个随机值在类定义时就固定了,之后每次调用都会复用这个初始值,不会重新生成随机选择。
  • 修复方法:把默认参数设为None,然后在函数内部判断并实时生成随机值:
import random
choices = ('Rock', 'Paper', 'Scissors')

class Player:
    def __init__(self, name='Computer', score=0, choice=None):
        self.name = name
        self.score = score
        # 实时生成随机选择,而非依赖默认参数
        self.choice = random.choice(choices) if choice is None else choice
        
    def get_name(self):
        return self.name
    
    def set_name(self, name):
        self.name = name
    
    def get_score(self):
        return self.score
    
    def increase_score(self):
        self.score += 1
        
    def set_choice(self, choice=None):
        # 每次调用都重新生成随机选择(如果未传入指定值)
        self.choice = random.choice(choices) if choice is None else choice
        
    def get_choice(self):
        return self.choice

修改后,每次调用set_choice()或创建电脑Player实例时,都会生成新的随机选择,保证每轮游戏的随机性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 06:35:21