简体   繁体   English

为什么我按下按钮时没有调用我的命令 function?

[英]Why is my command function not being called when I press a button?

I'm a bit of a newbie to Tkinter, so bear with me.我是 Tkinter 的新手,所以请耐心等待。 I'm making a simple game which involves buttons laid out in a grid.我正在制作一个简单的游戏,其中涉及以网格布局的按钮。 When one of these buttons is press, depending on their position, they move to a different spot on the grid.当按下其中一个按钮时,根据它们的 position,它们会移动到网格上的不同位置。 I feel like the mistake is probably a really small one but it continues to escape me.我觉得这个错误可能是一个非常小的错误,但它继续逃避我。

All code relevant to the issue:与问题相关的所有代码:

import numpy as np
from tkinter import *

class MoveableButton(Button):
    def __init__(self, location, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.location = location
    
    # the function I hope to call
    def move(self):
        self.location = "new location"
        self.grid(column=self.location[0], row=self.location[1])

root = Tk()
pieces = [MoveableButton("location_coordinates", root) for i in range(24)]
for i, piece in enumerate(pieces):
    piece.command = piece.move #the source of the problem

[piece.grid(column=i%5, row=i//5) for i, piece in enumerate(pieces)]
root.mainloop()

The problem is that you never assign a command to the button.问题是您永远不会为按钮分配命令。 You set the command attribute on the python object, but that's not the same as setting the option for the actual widget.您在 python object 上设置command属性,但这与为实际小部件设置选项不同。

You need to remove piece.command = piece.move and add piece.configure(command=piece.move)您需要删除piece.command = piece.move并添加piece.configure(command=piece.move)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM