2017-07-28 113 views
1

我正在创建一个Tkinter程序,允许用户将文本输入到一个漂亮的外观框而不是python外壳。从另一个文件获取变量 - python

因为我想在多个程序中使用它,所以我把它变成了一个可以在其他文件中使用的函数。

我可以得到它在另一个文件中运行,但不导入变量这里是我的代码。

文件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() 

文件2:

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

我得到的错误ImportError: cannot import name 'answer'

+0

你似乎并不被拯救“答案”在任何地方,所以也没有功能'on_button'之外存在。我认为可能有更好的方法来做到这一点 - 例如,在同一个函数中没有类和控制代码。 –

+0

文件1中没有“答案” –

+0

是的,它存在于最后一个函数中(底部) – Daniel

回答

1

answer is a local variable within按钮. If you want to import`它,你需要使它成为一个包属性:

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() 

不过,这是一个很奇怪的访问数据的方式。干净的模块设计可能有对象(SampleApp),并通过该应用程序的方法调用提取答案。更简单地说,为什么不从on_button返回该值?

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

...所以你的用法是

response = my_app.on_button() 
相关问题