【发布时间】:2015-01-20 13:46:46
【问题描述】:
我正在尝试构建一个 GUI。
当我直接执行应用程序(即双击 python 文件)时,我得到一个与导入它(mainloop)不同的结果(控制台输出)。
我希望它提供以下控制台输出:
c
d
e
f
g - from app
因为我希望主循环在作为模块导入后可以访问。
我正在尝试通过将其作为模块导入的外部文件来控制输入和输出。
我在运行文件时得到了预期的输出,但是当我将它作为模块导入时,它似乎在运行主循环,因为我得到了一个 Tkinter 主循环窗口输出。
代码如下:
class Application(Frame):
def __init__(self, master = None):
Frame.__init__(self, master)
self.text = Lines()
self.text.insert("\n\n\n\n\n")
self.waitingForInput = False
self.inText = ""
self.pack()
self.widgets()
def widgets(self):
self.L1 = Label(self)
self.L1["text"] = self.text.bottomLines
self.L1.pack(side = "top")
self.E1 = Entry(self)
self.E1["width"] = 40
self.E1.pack(side = "top")
self.B1 = Button(self)
self.B1["text"] = "Enter",
self.B1["command"] = self.giveInput
self.B1.pack(side = "top")
def giveInput(self):
if self.waitingForInput:
self.inText = self.B1.get()
self.waitingForInput = False
def getInput(self, output):
giveOutput(output)
self.waitingForInput = True
while True:
time.sleep(0.1)
if not self.waitingForInput:
break
return self.inText
def giveOutput(self, output):
self.text.insert(output)
self.L1["text"] = self.text.bottomLines
print self.text.bottomLines + " - from app"
root = Tk()
app = Application(master = root)
app.giveOutput("a \n b \n c \n d \n e \n f \n g")
Lines 类本质上是字符串中的一堆文本行,insert(x) 堆叠更多,bottomLines 访问堆栈的最后五行。
回到主题,当作为模块导入时,它会运行主循环,带有一个包含我假设为 5 个空行的标签、一个输入框和 "Enter" 按钮。我不想要这个。我想要和我之前直接运行文件时一样的结果。
我只希望在调用app.mainloop 方法时出现该框。
我做错了什么,哪里错了,我该如何改正?
【问题讨论】:
标签: python python-2.7 tkinter tk