Multiple operations from a single button tkinter

后端 未结 2 1277
轮回少年
轮回少年 2021-01-24 13:07

I have been writing a program for a GUI based plotter using matplotlib and tkinter. I have added a toplevel window for some options. I want to execute a function and quit the to

相关标签:
2条回答
  • 2021-01-24 13:25

    Buttons are designed for exactly this. Typically you would define a function or method that does whatever you want, then assign that method to the command attribute of the button:

    import Tkinter as tk
    import tkMessageBox
    
    class SampleApp(tk.Tk):
        def __init__(self):
            tk.Tk.__init__(self)
            button = tk.Button(text="Press me!", command=self.on_button)
            button.pack()
        def on_button(self):
            tkMessageBox.showinfo(message="Good-bye!")
            self.destroy()
    
    app = SampleApp()
    app.mainloop()
    
    0 讨论(0)
  • 2021-01-24 13:39

    The command option of a button lets you specify a function/method/callable object which will be called when the button is pressed.

    from Tkinter import *
    
    def buttonClicked(event):
        do_a_thing()
        do_another_thing()
        do_a_third_thing()
        #etc
    
    root = Tk()
    
    myButton = Button(root, text="Do Some Things", command=buttonClicked)
    myButton.pack()
    
    root.mainloop()
    

    You can quit a window by calling its destroy method.

    you seem to have another problem, which is that you can't destroy the top level window from inside the callback function, if you aren't in the scope that created the window. If you don't want to define a whole class just to hold a reference to the window, you can nest your function definitions:

    from Tkinter import *
    
    def makeMyWindow():
        root = Tk()
        def buttonClicked():
            print "Reticulating Splines..."
            print "Done. Goodbye!"
            #we can access root since we're inside the right scope, 
            #even if this function gets passed somewhere else as a callback
            root.destroy()
        myButton = Button(root, text="Do Some Things", command=buttonClicked)
        myButton.pack()
    
        root.mainloop()
    
    makeMyWindow()
    
    0 讨论(0)
提交回复
热议问题