TkInter按钮在网格上的坐标 [英] TkInter button coordinates on a grid

查看:85
本文介绍了TkInter按钮在网格上的坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在用TkInter制作GUI,GUI由内置于for循环中的网格组成,所有按钮都有1个变量(每个循环都会更新).我想知道如何获取我按下的任何按钮的坐标.(例如,当我按下按钮时,它会给出它在网格上的坐标).我使用了grid_info,但是它只获取最后创建的按钮的信息.感谢您的帮助:)

I'm currently making a GUI with TkInter, the GUI is made of a grid built in a for loop, with 1 variable for all buttons(It gets updated on every loop). I would like to know how I could get the coordinates of any button that i'd press. (For example, When I press, the button gives it's coordinates on the grid) I used grid_info but it only gets the info of the last button created. Thanks for helping me :)

推荐答案

您可以将行和列传递给与该函数关联的命令.最常见的两种方法是使用lambda或functools.partial.

You can pass the row and column to the command associated with the function. The two most common ways to do that are with lambda, or with functools.partial.

以下是使用lambda的示例:

Here's an example using lambda:

import tkinter as tk

def click(row, col):
    label.configure(text="you clicked row %s column %s" % (row, col))

root = tk.Tk()
for row in range(10):
    for col in range(10):
        button = tk.Button(root, text="%s,%s" % (row, col), 
                           command=lambda row=row, col=col: click(row, col))
        button.grid(row=row, column=col, sticky="nsew")
label = tk.Label(root, text="")
label.grid(row=10, column=0, columnspan=10, sticky="new")

root.grid_rowconfigure(10, weight=1)
root.grid_columnconfigure(10, weight=1)

root.mainloop()

这篇关于TkInter按钮在网格上的坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆