Tkinter语言 - 单击按钮执行功能时返回导入模块的打印



我编写了一些主要用于控制台的代码,但为了便于使用,我被要求为其创建一个简单的 GUI。在其中,我正在使用小部件设置主框架,并使用小部件命令调用我导入的函数。但是,导入的函数和模块都写入输出控制台。有没有办法返回输出字符串/控制台输出,以便在子进程运行时在 GUI 中更新?

示例脚本:

import Tkinter as *
import myModule1
class MyGUI(Frame):
def __init__(self):
# Initialization stuff.
self.initGUI()
def initGUI(self):
self.downloadButton = Button(text="Download data.")
self.downloadButton["command"] = myModule1.function
# This function from myModule1 will constantly print to the console as the process is performed - is there any way to have this displayed in the GUI as a ScrollBar? 
.....

或者,有没有办法在进程运行时显示对话框窗口?我问是因为我在 myModule1 及其子模块中嵌入了很多打印语句,这些语句将正在发生的事情返回到控制台。最好为GUI正在工作的用户显示这些内容,我将其转换为.exe,以便于使用它的人使用。

谢谢。

编辑:myModule1.function看起来像的示例:

import otherModule
def function1():
log = otherModule.function2():
if log == True:
print "Function 2 worked."
elif log == False:
print "Function 2 did not work."

但是,function2在执行计算时otherModule会打印到控制台。此处没有明确显示,但控制台输出本质上是一系列计算,然后是上面显示的示例 if/elif 子句。

这不会非常简单,但一种方法是在 GUI 中创建一个方法或函数,用于写入文本小部件或其他一些内容可以轻松更新的小部件。我称之为outputMethod.然后,将此函数或方法传递给myModule1.function(outputMethod)。在 module1.函数中,将 print 语句替换为outputMethod调用,为其提供适当的参数。如果没有看到 module1.function,就很难提供一个完整的示例。在 OP 发布 myModule1 示例代码后添加了以下示例。

from Tkinter import *
import myModule1
class MyGUI(Frame):
def __init__(self, parent):
# Initialization stuff.
self.initGUI(parent)
def initGUI(self, parent):
Frame.__init__(self, parent)
self.grid_rowconfigure(1, weight=1)
self.grid_columnconfigure(1, weight=1)
self.pack(expand='yes', fill='both')
self.downloadButton = Button(self, text="Download data.")
self.downloadButton["command"] = lambda m=self.outputMethod: myModule1.function(m)
self.text = Text(self)
self.downloadButton.grid(row=0, column=0)
self.text.grid(row=1, column=0, sticky='news')
self.sy = Scrollbar(self, command=self.text.yview)
self.text['yscrollcommand'] = self.sy.set
self.sy.grid(row=1, column=1, sticky='nsw')

def outputMethod(self, the_output):
self.text.insert('end', the_output + 'n')
# Scroll to the last line in the text widget.
self.text.see('end')
if __name__ == '__main__':
# Makes the module runable from the command line.
# At the command prompt type python gui_module_name.py
root = Tk()
app = MyGUI(root)
# Cause the GUI to display and enter event loop
root.mainloop()

现在对于模块 1...

def function(log):
# Note that log is merely a pointer to 'outputMethod' in the GUI module.
log("Here is a string you should see in the GUI")
log("And this should appear after it.")
# Now demonstrate the autoscrolling set up in outputMethod...
for i in range(50):
log("Inserted another row at line" + str(i + 2))

最新更新