user2469202
user2469202

Reputation: 336

global variable in Tkinter

I am a novice Python/Tkinter user and not clear for me how to pass widget content. I supposed usrtext is a global variable - but it prints an empty string. However, Text has real content. What is the way to pass correctly?

class App(object):

    def __init__(self, root):
        frame = Frame(root)
        frame.grid()
        usrtext = Text(bg = "light yellow", fg = "black",relief=SUNKEN)
        usrtext.grid(row=0, columnspan=16, rowspan=2, sticky=W+E+N+S, padx=5, pady=5)
...
...
def do_it():
    print usrtext       // I'd like to see usrtext _here_
...
...
root = Tk()
root.title("My First Attempt")
usrtext=StringVar()
usrtext=""
...
...
butt1 = Button(root, text='Do it', height=1, width=10, relief=RAISED, command=do_it)
butt1.grid(row=4, column=14)

app = App(root)
root.mainloop()

Upvotes: 2

Views: 1947

Answers (2)

furas
furas

Reputation: 142641

To get text from Text you use

  • get(start,end) to get text from Text
  • insert(position, text) to add text to Text

usrtext.insert(END, "Hello World")

print usrtext.get(1.0, END)

see more: The Tkinter Text Widget

By the way: you use usrtext to two elements

usrtext=StringVar()
usrtext=Text()

so in one moment usrtext is StringVar in other Text - I think it is not what you expect.

Upvotes: 1

Fiver
Fiver

Reputation: 10167

Try putting everything inside your application class, then you can reference the widgets via self. You've got the same variable name in multiple places but they don't refer to the same thing.

import Tkinter


class Application(Tkinter.Frame):
    def __init__(self, master):
        Tkinter.Frame.__init__(self, master)
        self.parent = master

        frame = Tkinter.Frame(self)

        self.user_text = Tkinter.Text(frame, relief=Tkinter.SOLID, borderwidth=2)
        self.user_text.grid(
            row=0,
            columnspan=16,
            rowspan=2,
            sticky=Tkinter.W+Tkinter.E+Tkinter.N+Tkinter.S,
            padx=5,
            pady=5)

        self.butt1 = Tkinter.Button(frame, text='Do it!', command=self.do_it)
        self.butt1.grid(row=2, columnspan=16)

        frame.pack(fill=Tkinter.BOTH, expand=1, side=Tkinter.BOTTOM)
        self.pack(fill=Tkinter.BOTH, expand=1)

    def do_it(self):
        user_text_string = self.user_text.get(1.0, Tkinter.END)
        print user_text_string


def main():
    root = Tkinter.Tk()
    app = Application(root)
    app.mainloop()

if __name__ == '__main__':
    main()

Upvotes: 1

Related Questions