How to get grid information from pressed Button in tkinter?

前端 未结 3 1989
深忆病人
深忆病人 2021-01-14 13:13

I need to create table of buttons using Tkinter in Python 2.7, which has n rows and n columns, and has no button in bottom right corner.

P

3条回答
  •  不思量自难忘°
    2021-01-14 14:03

    Could you do something like create the grid of buttons up front, but include a hidden button in the blank space? Then when the button is clicked hide the clicked one and display the hidden one. Then you don't have to worry about moving buttons around, unless you need the actual button object to move for some reason.

    Edit to enhance answer from comments:

    Below is a simple example of hiding a button and it shows how to track the buttons as well, unless I screwed up moving it to the editor. This can be translated to a list or dictionary of buttons or whatever need be. You'd also need to determine find a way to register the local buttons or add some context to know which one to show or hide.

    from Tkinter import Button, Frame, Tk
    
    
    class myButton(Button):
    
        def __init__(self, *args, **kwargs):
            Button.__init__(self, *args, command=self.hideShowButton,
                            ** kwargs)
            self.visible = True
    
        def hideShowButton(self):
            self.visible = False
            self.pack_forget()
    
    window = Tk()
    frame = Frame(window)
    frame.pack()
    b1 = myButton(window, text="b1")
    b1.pack()
    b2 = myButton(window, text="b2")
    b2.pack()
    b3 = myButton(window, text="b3")
    b3.pack()
    window.wait_window(window)
    print "At the end of the run b1 was %s, b2 was %s, b3 was %s" % (str(b1.visible), str(b2.visible), str(b3.visible))
    

提交回复
热议问题