1

I am creating a Tkinter program that allows the user to enter text into a nice looking box rather than the python shell.

As I would like to use this in multiple programs I made into a function that can be used in other files.

I can get it to run in another file, but not import the variable here is my code.

File 1:

import tkinter as tk

def input_text(label_text, button_text):
    class SampleApp(tk.Tk):

        def __init__(self):
            tk.Tk.__init__(self)
            self.entry = tk.Entry(self)
            self.button = tk.Button(self, text=button_text, command=self.on_button)
            self.label = tk.Label(self, text=label_text)
            self.label.pack(side = 'top', pady = 5)
            self.button.pack(side = 'bottom', pady = 5)
            self.entry.pack()


        def on_button(self):
            answer = self.entry.get()
            self.destroy()


    w = SampleApp()
    w.resizable(width=True, height=True)
    w.geometry('{}x{}'.format(180, 90))
    w.mainloop()

File 2:

import text_input as ti
from text_input import answer
ti.input_text('Enter some text', 'OK')

I get the error ImportError: cannot import name 'answer'

4
  • You don't seem to be saving 'answer' anywhere, so it doesn't exist outside the function on_button. I think there's probably a better way to do this - not having the class and control code in the same function, for example. Commented Jul 28, 2017 at 18:44
  • There is no "answer" in file 1 Commented Jul 28, 2017 at 18:44
  • Yes there is it is in the last function(at the bottom) Commented Jul 28, 2017 at 18:46
  • @SimonFraser How could I save answer elsewhere? Commented Jul 28, 2017 at 18:46

1 Answer 1

1

answer is a local variable withinbutton. If you want toimport` it, you need to make it a package attribute:

import tkinter as tk

global answer

def input_text(label_text, button_text):
    class SampleApp(tk.Tk):
    ...

        def on_button(self):
            global answer
            answer = self.entry.get()

However, this is a very strange way to access the data. Clean module design would likely have the object (SampleApp) at hand, and extract the answer with a method call for that app. More simply, why not just return that value from on_button?

    def on_button(self):
        answer = self.entry.get()
        self.destroy()
        return answer

... so your usage would be

response = my_app.on_button()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.