Python tkinter 按钮 'out of place' / 无法正常工作
Python tkinter Buttons are 'out of place' / not working properly
你好 python 用户...
我试图创建我的第一个 GUI 编写井字游戏程序,但我 运行 遇到了关于网格上 9 个按钮的问题。以下是生成按钮的部分代码:
button = 0
for x in range(3):
for y in range(3):
button = Button(root, text= " ", font=("Helvetica", 20), height=3, width=6, bg="SystemButtonFace", command=lambda button=button: b_click(button))
button.grid(row = x, column = y)
点击函数如下所示:
def b_click(b):
global clicked
if b["text"] == " " and clicked == True:
b["text"] = "X"
clicked = False
elif b["text"] == " " and clicked == False:
b["text"] = "O"
clicked = True
else:
messagebox.showerror("Tic Tac Toe", "Hey! That box has already been selected \nPick another box...")
我的问题是,每当我在 GUI 上单击一个按钮时,它都会选择并在我最初选择的按钮左侧的按钮上使用 b_click(b)...
帮助将不胜感激...
看看这个脚本:
import tkinter as tk
from functools import partial
def b_click(button):
button.config(text="X")
root = tk.Tk()
for x in range(3):
for y in range(3):
button = tk.Button(root, text=" ")
command = partial(b_click, button)
button.config(command=command)
button.grid(row=x, column=y)
root.mainloop()
它使用 functools.partial
和 <tkinter.Button>.config(...)
将按钮传递给函数。从那里你可以用按钮做任何你喜欢的事情。
编辑:
functools.partial
类似于 labmda
但您不需要 button=button
部分。它至少需要 1 个参数(函数名称),其余 arguments/key 个单词参数在调用时传递给函数。
所以
x = partial(function, arg1, arg2, kwarg1="")
x(arg3)
将与 function(arg1, arg2, arg3, kwarg1="text")
相同。
你好 python 用户...
我试图创建我的第一个 GUI 编写井字游戏程序,但我 运行 遇到了关于网格上 9 个按钮的问题。以下是生成按钮的部分代码:
button = 0
for x in range(3):
for y in range(3):
button = Button(root, text= " ", font=("Helvetica", 20), height=3, width=6, bg="SystemButtonFace", command=lambda button=button: b_click(button))
button.grid(row = x, column = y)
点击函数如下所示:
def b_click(b):
global clicked
if b["text"] == " " and clicked == True:
b["text"] = "X"
clicked = False
elif b["text"] == " " and clicked == False:
b["text"] = "O"
clicked = True
else:
messagebox.showerror("Tic Tac Toe", "Hey! That box has already been selected \nPick another box...")
我的问题是,每当我在 GUI 上单击一个按钮时,它都会选择并在我最初选择的按钮左侧的按钮上使用 b_click(b)...
帮助将不胜感激...
看看这个脚本:
import tkinter as tk
from functools import partial
def b_click(button):
button.config(text="X")
root = tk.Tk()
for x in range(3):
for y in range(3):
button = tk.Button(root, text=" ")
command = partial(b_click, button)
button.config(command=command)
button.grid(row=x, column=y)
root.mainloop()
它使用 functools.partial
和 <tkinter.Button>.config(...)
将按钮传递给函数。从那里你可以用按钮做任何你喜欢的事情。
编辑:
functools.partial
类似于 labmda
但您不需要 button=button
部分。它至少需要 1 个参数(函数名称),其余 arguments/key 个单词参数在调用时传递给函数。
所以
x = partial(function, arg1, arg2, kwarg1="")
x(arg3)
将与 function(arg1, arg2, arg3, kwarg1="text")
相同。