Python全局变量未被识别,提示‘local variable P1o referenced before assignment’
问题解决:全局变量未识别及相关错误修复
你的错误主要来自三个核心问题:全局变量在函数内修改未声明、变量初始类型错误、方法使用不当,还有一处事件判断的笔误。以下是具体修复方案:
1. 声明全局变量
在Battleship1()函数开头添加global P1o, P2o,告诉Python函数内要引用的是全局作用域的这两个变量,否则Python会默认将其视为局部变量,导致"referenced before assignment"错误。
2. 修正变量初始类型
你初始把P1o和P2o设为空字符串(""),但后续要调用append方法(仅列表支持),所以要改成列表初始化:
P1o = [] P2o = []
3. 正确使用append方法
append是列表的原地修改方法,返回值为None,不能用P1o = P1o.append(...)这种赋值方式,直接调用即可:
# 错误写法 # P1o = P1o.append(int(values['input_\P1o'])) # 正确写法 P1o.append(int(values['input_\P1o']))
4. 修复事件判断笔误
PySimpleGUI的事件名与按钮文本一致,你写的elif event == 'cancel'应该改为elif event == 'Cancel'(大写C),否则点击Cancel按钮不会触发对应逻辑。另外第二个Submit块里错误地给P1o追加值,应该改为P2o,对应玩家2的输入。
修正后的完整代码示例
# import pwinput import PySimpleGUI as sg # 初始化为列表而非字符串 P1o = [] P2o = [] MAX_ROWS = MAX_COL = 10 def Battleship1(): # 声明要使用的全局变量 global P1o, P2o layout = [ [sg.Text('Player1 please enter your ship positions'), sg.InputText('', size=(10,1), key='input_\P1o')], [sg.Submit(), sg.Cancel()] ] window = sg.Window('player1 values', layout) while True: event, values = window.read() if event == sg.WIN_CLOSED: break elif event == 'Submit': # 直接调用append,无需赋值 P1o.append(int(values['input_\P1o'])) window.close() elif event == 'Cancel': # 修正为大写Cancel window.close() break layout = [ [sg.Text('Player2 please enter your ship positions'), sg.InputText('', size=(10,1), key='input_\P2o')], [sg.Submit(), sg.Cancel()] ] window = sg.Window('player2 values', layout) while True: event, values = window.read() if event == sg.WIN_CLOSED: break if event == 'Submit': # 这里应该给P2o追加值,不是P1o P2o.append(int(values['input_\P2o'])) # turn()和turn_()需要确保已定义,否则会报错 # turn() # turn_() if event == 'Cancel': # 修正为大写Cancel window.close() break """ i set up the multiplayer function""" layout = [ [sg.Text("Welcome to battleship!!\nObject of the game is to sink all five of your enemy's ships!!!\nlabel your ship positions with a number (0-9)\n and another number (0-9)\n and separate each position with spaces e.g 1,2 2,3 3,4")], [sg.Button('Single Player'), sg.Button('Multiplayer')] ] window = sg.Window('Menu', layout) while True: event, values = window.read() if event == sg.WIN_CLOSED: break if event == 'Multiplayer': window.close() Battleship1() break
内容的提问来源于stack exchange,提问作者Thunder061005
相关产品推荐
相关产品推荐

