Asperoth
Asperoth

Reputation: 1

Want to use a Tkinter button for string input, then closing the button window and continue on

This seems like it should be incredibly easy to do, but I'm struggling. Programming is not my main background, so I'm lacking a lot of the basics, but I'm trying to learn.

The issue I'm dealing with is I want to use a Tkinter button to display a list of buttons (currently only one), and when one of those buttons is pressed, it inputs the text from said button into a string variable, closes the button window, and continues on with the code.

Here's what I've got for this section:

    root = tk.Tk()

    def data(name):
       global query 
       query = name


    B = tk.Button(root, text ='LogID', command = data('LogID'))

    B.pack()
    root.mainloop()

    print query

If this seems perhaps a little jumbled or slapdash, it's because it is.

There's code before, and code after this section. I'd like the window to close (root.destroy()) when the button is pressed and for the code to print the text from 'query' so I know it's passed the value to it.

When I run it, it hangs on the root.mainloop() section, or seems to. And I'll be honest, I don't fully understand what that does in the code, all I know is it needs it.

Upvotes: 0

Views: 1940

Answers (1)

Honest Abe
Honest Abe

Reputation: 8759

Because I see you are already using global variables,
I'm going to answer your question with an example of
how to make your application a subclass of Tkinter.Tk (tkinter.Tk in python 3).

import Tkinter as tk

class Application(tk.Tk):

    def __init__(self):
        tk.Tk.__init__(self)
        self.title('Hello world!')
        self.data = None

        self.helloButton = tk.Button(self, width=12, text='Hello',
                    command=lambda x='hi': self.say_hi(x))
        self.helloButton.grid(row=0, column=1, padx=8, pady=8)

    def say_hi(self, x):
        self.data = x
        self.withdraw()
        self.secondWin = tk.Toplevel(self)
        self.secondWin.grid()
        self.output = tk.Entry(self.secondWin)
        self.output.insert(0, x)
        self.output.grid()
        self.quitButton = tk.Button(self.secondWin, text='Quit', bg='tan',
                                    command=self.close_app)
        self.quitButton.grid()

    def close_app(self):
        self.destroy()

app = Application()
app.mainloop()

The variable self.data can be used by any method of your class;
therefore, you do not have to use the global keyword.
The mainloop keeps your tkinter application 'running' and handles events.
Notice that I didn't destroy the first window, but hid it using the withdraw method.
It's just another option you might be interested in. You can use deiconify to make it visible (more info here). The second window is a Toplevel widget, which is what you use to create secondary windows.

I wrote a more educational example that can be found here.

Upvotes: 2

Related Questions