【发布时间】:2020-02-22 12:12:02
【问题描述】:
大家好,
我一直致力于使用 PySimpleGUI 为我的井字游戏创建 GUI。我的代码如下:
import PySimpleGUI as sg
import random
board_layout1 = {(2,0):" ", (2,1):" ", (2,2): " ", (1,0): " ", (1,1): " ", (1,2): " ", (0,0): " ", (0,1): " ", (0,2): " "}
电路板布局基于:
然后我创建了一个界面来接收用户输入(即名称并选择 X 或 O 符号)。
layout = [
[sg.Text("Please enter your Name and your opponent's name")],
[sg.Text('Name', size=(15, 1)), sg.InputText('')],
[sg.Text('Name of opponent', size=(15, 1)), sg.InputText('')],
[sg.Frame(layout=[
[sg.Radio('X', "RADIO1", default=True, size=(10,1)), sg.Radio('O', "RADIO1")]], title='Options',title_color='red', relief=sg.RELIEF_SUNKEN, tooltip='Use these to set flags')],
[sg.Submit(), sg.Cancel()]
]
window = sg.Window('Tic Tac Toe Game').Layout(layout)
button, events = window.Read()
print(events)
window.close()
player1, player2, player1_event, player2_event = events[0], events[1], events[2], events[3]
player1 和 player2 将返回他们的名字。 Player1_event 和 player2_event 将返回 True 或 False。当我使用复选框时,如果我选中它,events2 将为 True,而 events[3] 将为 False。
然后我分别分配标记。
if player1_event == True:
player1_marker, player2_marker = ("X", "O")
else:
player1_marker, player2_marker = ("O", "X")
现在,我将为板子创建 GUI。
def board_gui():
max_row = max_col = 3
layout = [[sg.Button(' ', size=(8, 4), key=(i,j), pad=(0,0)) for j in range(max_col)] for i in range(max_col)]
window = sg.Window('Tictactoe', layout)
button, events = window.Read()
return button
window.close()
接下来(问题出在哪里),我创建了相应地更新板的函数。因此,假设 play1 首先开始并且他决定选择“X”作为他的标记。他选择了第一个网格并单击它。它标记了“X”。所以下一次点击应该属于play2,它的标记是'O'。我的代码似乎在为第二次点击更新标记时出现问题。
我做了什么:
def board_gui_update(marker):
max_row = max_col = 3
layout = [[sg.Button(' ', size=(8, 4), key=(i,j), pad=(0,0)) for j in range(max_col)] for i in range(max_col)]
window = sg.Window('Tictactoe', layout)
while True:
button, events = window.Read()
if button in (None, 'Exit'):
break
window[button].update(marker)
window.close()
我尝试过的:
def board_gui_update(marker):
max_row = max_col = 3
layout = [[sg.Button(' ', size=(8, 4), key=(i,j), pad=(0,0)) for j in range(max_col)] for i in range(max_col)]
window = sg.Window('Tictactoe', layout)
while True:
button, events = window.Read()
if button in (None, 'Exit'):
break
if marker == player1_marker:
turn = player1
if turn == player1:
window[button].update(player1_marker)
turn = player2
else:
window[button].update(player2_marker)
else:
if marker == player2_marker:
turn = player2
if turn == player2:
window[button].update(player2_marker)
turn = player1
else:
window[button].update(player1_marker)
window.close()
这里似乎也不起作用。我查看了涉及 tkinter 的文档和解决方案,但似乎没有任何东西能够更新标记。
您可以在此snapshot 中查看问题。
【问题讨论】:
-
如果您将代码完整地发布在某处会很有帮助。您可能想在 PySimpleGUI GitHub 上提交问题以获得一些帮助。我上次尝试更新按钮上的文本效果很好。我不太确定你描述的问题。您是说您无法更改按钮文本吗?如果是这样,请尝试编写一个小程序来查看是否存在问题。
-
遵循 PySimpleGUI 示例和文档中的编码约定会很有帮助。这行代码具有误导性且不正确 - 按钮、事件 = window.Read()。它应该读取事件,值 = window.Read()。第二个参数不是事件,它是来自窗口的值字典。第一个参数是事件。有时这可能是一个按钮,但也可能是其他东西,因此将其标记为按钮可能会造成混淆。
标签: python pysimplegui