首页 > 解决方案 > 如何在 tkinter 窗口中打印项目?

问题描述

我有这个代码:

root= tk.Tk()

button1 = tk.Button(root, text='Button', command=lambda:print("Click"))
button1.grid(row=1, column=1)

Label = tk.Label(root, text="Text")
Label.grid(row=1, column=2)

root.mainloop()

我想得到什么:

Button:(1, 1), Label:(1, 2)

如何在根目录中打印项目及其目的地?

标签: pythontkinter

解决方案


如果您只想获取有关的信息grid,使用grid_info()可以获取有关小部件的信息。要获取所有小部件root,只需使用root.winfo_children()

import tkinter as tk

root = tk.Tk()

button1 = tk.Button(root, text='Button', command=lambda:print("Click"))
button1.grid(row=1, column=1)

Label = tk.Label(root, text="Text")
Label.grid(row=1, column=2)

for widget in root.winfo_children():
    print(f"{widget.widgetName}:({ widget.grid_info()['row']}, {widget.grid_info()['column']})")

root.mainloop()

结果:

button:(1, 1)
label:(1, 2)

推荐阅读