简体   繁体   中英

basic question about tkinter buttons

I'm new to using tkinter and GUI programming in general so this may be a pretty basic question. Anyway, suppose I have a set of buttons for the user to choose from and what I want is a list of all the button objects that were clicked by the user. Basically, I want to know which buttons the user clicked.

Here's a good website covering Python events that should guide you:

http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm

It sounded like you might want something akin to a checkbox, if so:

Cannot understand how to get data from checklistbox in wxpython

On each of the buttons you could set the command to add themselves to a list of clicked buttons.

clicked = []
foo = Button(root, text='bar', command=lambda self:clicked.append(self))

Not sure if the syntax is all correct, but that's the basic idea.

Here is a simple example of what you could do to find out if a button has or has not been pressed yet.

import tkinter.ttk, functools

class Example(tkinter.Tk):

    def __init__(self, buttons):
        super().__init__()
        self.button_set = set()
        for button in range(buttons):
            button = tkinter.ttk.Button(self, text='Button '+str(button))
            button.pack()
            self.button_set.add(button)
        self.setup_buttons()
        self.bind('<Escape>', self.check_buttons)
        self.mainloop()

    def setup_buttons(self):
        for button in self.button_set:
            button['command'] = \
                functools.partial(setattr, button, 'pressed', True)
            button.pressed = False

    def check_buttons(self, event):
        for button in self.button_set:
            print('Button {} has{} been pressed.'.format(id(button),
                (' not', '')[button.pressed]))

if __name__ == '__main__':
    Example(5)

When the code is run, you may press the Escape key to get a printout in the console of what buttons have been pressed. Pressing the buttons will set their pressed attribute to true, and you can get another printout of what buttons have been pressed. Programatically, you would follow the example in the check_buttons method to find out if a button has been pressed or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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