模块从tkinter Widget导入

时间:2013-12-11 05:07:16

标签: python-3.x tkinter python-import

不久前,我问了一个关于如何从输入语句导入的问题。搞定了。现在我将我冗长的代码升级为用户的GUI。同样的问题。如何根据tkinter小部件Entry中的用户输入导入模块。 我最初有:

var1=__import__(input("Enter a module: "))

尝试过这样的事情:

import tkinter
var1=__import__(tkinter.Entry(top, bd=5)).pack()

一些不同的措辞都导致了基本错误:

TypeError: __import__() argument 1 must be str, not Entry

我还有一些不同的方法可以尝试。例如:

var1=Entry(top, bd=5).grid(row=7)
var2=Entry.get(var1)
var=__import__(var2)

这给了我一个相当可怕的错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python33\lib\tkinter\__init__.py", line 1475, in __call__
    return self.func(*args)
  File "C:\Python33\Doc\Project\testing.py", line 21, in finish
    var2=Entry.get(var1)
  File "C:\Python33\lib\tkinter\__init__.py", line 2512, in get
    return self.tk.call(self._w, 'get')
AttributeError: 'NoneType' object has no attribute 'tk'

1 个答案:

答案 0 :(得分:3)

您需要Entry 实例才能使用它。

这样:

my_entry = Entry(top, bd=5) # you get object (Entry instance)
my_entry.grid(row=7) # you call object method grid()

entry_text = my_entry.get() # you call object method get()

var = __import__(entry_text)

<强>顺便说一句:

这样你就得到了grid()函数的结果,而不是Entry实例。

var1 = Entry(top, bd=5).grid(row=7) # grid() returns always None

my_entry = Entry(top, bd=5)
grid_result = my_entry.grid(row=7) # grid() returns always None
var1 = grid_result

在此代码中,您尝试打包()导入的库:)

var1 = __import__(tkinter.Entry(top, bd=5)).pack()

my_entry = Entry(top, bd=5) # you get object 
imported_library = __import__(my_entry) # object can't be argument for __import__
var1 = imported_library.pack() # you can't pack library