我使用PyCharm IDE制作了井字游戏。我试图使其与tkinter一起运行,但出现了一些问题。
我的程序要求用户在X和O之间进行选择,以及X是播放第一还是第二。同样,如果您输入的答案不正确,程序将告诉用户重新键入他/她的答案(带有while语句)。在tkinter上,我无法做到这一点,例如,当程序询问“您要X还是O”并且用户键入X然后输入ok_button
时,它不会在任何地方存储该信息。而且,如果我尝试放入while
循环,则会进行无限循环(因为它会循环遍历用户单击的ok
的第一个答案)
我的问题是,既然tkinter使用类和函数运行(至少我不知道其他事情),我该如何创建序列。例如:程序询问“您想成为X还是O?” ,在输入正确的输入后,程序应询问“您想成为第一还是第二?” < / em>。
from tkinter import *
def name_choose(x):
# "print" message to Label
message["text"] = player_decide(x)[2]
# how do i store that info below ? so i can use it later
player_1 =player_decide(x)[0]
player_2 =player_decide(x)[1]
window = Tk()
....
message = Label(window_frame1)
message.place(relwidth=0.5, relheight=1)
entry = Entry(window_frame1)
entry.place(relx=0.55, relwidth=0.2, relheight=1)
button_Ok = Button(window_frame1, text="Ok", command = lambda: name_choose(entry.get()) )
button_Ok.place(relx=0.8, relwidth=0.2, relheight=1)
....
window.mainloop()
def player_decide(player_1):
player_2 = ""
if player_1.upper() == "X":
message = "Player 1 : X , Player 2 : O"
player_2 = "O"
game_status = 1
elif player_1.upper() == "O":
player_2 = "X"
message = "Player 1 : O , Player 2 : X"
game_status = 1
else:
message = "Retry Input"
game_status = 0
return player_1, player_2, message , game_status
答案 0 :(得分:0)
这是固定代码:
from tkinter import *
def name_choose(x):
# "print" message to Label
message["text"] = player_decide(x)[2]
# how do i store that info below ? so i can use it later
player_1 =player_decide(x)[0]
player_2 =player_decide(x)[1]
window = Tk()
....
message = Label(window_frame1)
message.place(relwidth=0.5, relheight=1)
entry = Entry(window_frame1)
entry.place(relx=0.55, relwidth=0.2, relheight=1)
button_Ok = Button(window_frame1, text="Ok", command = lambda: name_choose(entry.get()) )
button_Ok.place(relx=0.8, relwidth=0.2, relheight=1)
....
def player_decide(player_1):
player_2 = ""
if player_1.upper() == "X":
message = "Player 1 : X , Player 2 : O"
player_2 = "O"
game_status = 1
elif player_1.upper() == "O":
player_2 = "X"
message = "Player 1 : O , Player 2 : X"
game_status = 1
else:
message = "Retry Input"
game_status = 0
return player_1, player_2, message , game_status
window.mainloop()
问题是因为您在mainloop之后定义了函数。确保在主循环启动之前运行所有代码。