如何删除由循环制作的按钮

编程入门 行业动态 更新时间:2024-10-26 16:32:32
本文介绍了如何删除由循环制作的按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..
  from tkinter import *


class Main:

    def __init__(self, root):

        for i in range(0, 9):
            for k in range(0, 9):
                Button(root, text=" ").grid(row=i, column=k)


        root.mainloop()


root = Tk()

x = Main(root)

如果按钮未分配给变量,如何在单击时删除按钮?

How do I delete a button when it is clicked if it isn't assigned to a variable ?

推荐答案

问题:如果按钮没有分配给变量,我如何在它被点击时删除它?

Question: How do I delete a button when it is clicked if it isn't assigned to a variable ?

核心点:

.bind('', self.on_click)

使用事件回调,为您提供 Grid 坐标以将移除的 Button 替换为其他小部件,例如带有图像.

Using a event callback, provides you with the Grid coordinate to replace the removed Button with a other widget, like a Label with a image.

import tkinter as tk


class Button(tk.Button):
    def __init__(self, parent, **kwargs):
        super().__init__(parent, **kwargs)
        self.bind('<Button-1>', self.on_click)

    def on_click(self, event):
        w = event.widget
        row, column = w.grid_info().get('row'), w.grid_info().get('column')
        print('coord:{}'.format((row, column)))
        w.destroy()


class App(tk.Tk):
    def __init__(self):
        super().__init__()

        for row in range(0, 9):
            for column in range(0, 9):
                Button(self, text=" ").grid(row=row, column=column)


if __name__ == '__main__':
    App().mainloop()

这篇关于如何删除由循环制作的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 05:32:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1390149.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:按钮

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!