【问题标题】:Python tkinter Buttons are 'out of place' / not working properlyPython tkinter 按钮“不合适”/无法正常工作
【发布时间】:2021-03-06 11:46:18
【问题描述】:

你好狂热的 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)...

我们将不胜感激...

【问题讨论】:

  • 你知道第一个按钮的命令是b_click(0),对吧?
  • 那么你会推荐什么?我觉得我一直在尝试一切来尝试解决这个问题......

标签: python tkinter button default-arguments


【解决方案1】:

看看这个脚本:

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 个参数(函数名),其余参数/关键字参数在调用时传递给函数。

所以

x = partial(function, arg1, arg2, kwarg1="")
x(arg3)

将与function(arg1, arg2, arg3, kwarg1="text") 相同。

【讨论】:

  • 病了,这很好用!我尝试查看functools.partial 的文档,但我不确定我是否完全理解它......需要解释一下吗?
  • @SomeCoderOnTheWeb 我加了一个解释(不是最好的)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-31
  • 1970-01-01
  • 2013-08-26
  • 1970-01-01
相关资源
最近更新 更多