我正在用python / tkinter制作井字游戏。
所以我使用xxx.Button.grid绘制了一个3x3的网格,现在我想为每个按钮分配属性,以便我可以输入将确定“ X”或“ O”的文本
我想做的是给一个保留值为0的空方块分配1或(-1),从而确定X和O。我希望以这种方式进行尝试将有助于我找到获胜条件。
from tkinter import Tk, Canvas, Frame, Grid, Button, N, S, E, W
root = Tk()
canvas = Canvas()
frame = Frame(root)
root.title("DJB")
root.minsize(300, 300)
root.resizable(False, False)
root.configure(bg='black')
# --------------------------------------------
Grid.rowconfigure(root, 3, weight=1)
Grid.columnconfigure(root, 3, weight=1)
frame=Frame(root)
frame.grid(row=3, column=3, sticky=N+S+E+W)
for row_index in range(3):
Grid.rowconfigure(frame, row_index, weight=1)
for col_index in range(3):
Grid.columnconfigure(frame, col_index, weight=1)
btn = Button(frame, bg="white") #create a button inside frame
btn.grid(row=row_index, column=col_index, sticky=N+S+E+W)
如果我只需向每个按钮输入代码,它将使我的项目继续进行。最终,我将创建一个按钮网格,当按下按钮时,该按钮将显示文本并在+1和-1之间切换整数。
答案 0 :(得分:0)
您可以通过widget["text"]
检查按钮文本。将其作为命令传递以动态获取值:
from tkinter import Tk, Canvas, Frame, Grid, Button, N, S, E, W
root = Tk()
canvas = Canvas()
frame = Frame(root)
root.title("DJB")
root.minsize(300, 300)
root.resizable(False, False)
root.configure(bg='black')
# --------------------------------------------
Grid.rowconfigure(root, 3, weight=1)
Grid.columnconfigure(root, 3, weight=1)
frame.grid(row=3, column=3, sticky=N+S+E+W)
def get_value(widget):
if widget["text"] == "" or widget["text"] == "X":
widget["text"] = "O"
#value = 1
else:
widget["text"] = "X"
#value = -1
for row_index in range(3):
Grid.rowconfigure(frame, row_index, weight=1)
for col_index in range(3):
Grid.columnconfigure(frame, col_index, weight=1)
btn = Button(frame, bg="white",font="Arial 40 bold",width=3)
btn.config(command=lambda x=btn: get_value(x))
btn.grid(row=row_index, column=col_index, sticky=N+S+E+W)
root.mainloop()
答案 1 :(得分:0)
我更改了您的代码,请告诉我这是否对您有帮助。
我添加了一个函数,该函数将返回按下的按钮的ID。
功能:
from tkinter import Tk, Canvas, Frame, Grid, Button, N, S, E, W, mainloop
from functools import partial
root = Tk()
canvas = Canvas()
frame = Frame(root)
root.title("DJB")
root.minsize(300, 300)
root.resizable(False, False)
root.configure(bg='black')
# --------------------------------------------
Grid.rowconfigure(root, 3, weight=1)
Grid.columnconfigure(root, 3, weight=1)
frame=Frame(root)
frame.grid(row=3, column=3, sticky=N+S+E+W)
# This Function will return Button id
def button_id(id):
print("Button {} is pressed".format(id))
return id
id = 1
for row_index in range(3):
Grid.rowconfigure(frame, row_index, weight=1)
for col_index in range(3):
Grid.columnconfigure(frame, col_index, weight=1)
btn = Button(frame, bg="white", command = partial(button_id, id=id)) #create a button inside frame
btn.grid(row=row_index, column=col_index, sticky=N+S+E+W)
id += 1
mainloop()
完整代码:
<TextInput
style={{height: 40, borderColor: 'gray', borderWidth: 1,width:'50%'}}
onChangeText={(text) => this.setState({name: text })}
placeholder="Name"
/>