开发者

basic question about tkinter buttons [duplicate]

This question already has answers here: 开发者_开发百科 How to pass arguments to a Button command in Tkinter? (18 answers) Closed 7 months ago.

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.


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'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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜