这个问题是关于在 Python 2.7.x 中编程的
我想编写一个程序,其中存在两个函数:一个是从用户那里获取输入的方法,另一个是显示输入。两者都应该在 GUI 中完成。我们将第一个函数称为 GET TEXT 函数,将第二个函数称为 SHOW TEXT 函数;我的策略是打开一个 GUI,显示一个文本框,然后放一个按钮去显示文本功能。然后,SHOW TEXT函数的第一行就是关闭GET TEXT函数打开的窗口,获取输入文本的值,并在另一个GUI中打印出来。
所以,我尝试这样做,
from Tkinter import *
import tkMessageBox
def texttobeenteredhere():
application = Tk()
textbox = Text(application)
textbox.pack()
submitbutton = Button(application, text="OK", command=showinputtext)
submitbutton.pack()
application.mainloop()
def showinputtext():
application.quit()
thetext = textbox.get()
print "You typed", thetext
texttobeenteredhere()
我有一些我无法理解的错误,但我希望你能理解我的想法,尽管我的解释可能非常糟糕。请为我的问题提出一个解决方案,其中 GET TEXT 函数和 SHOW TEXT 函数必须分别存在于代码中。
编辑:感谢 Josselin 在 python 中引入语法类。其实我想说的是,我想让程序打开一个窗口来获取用户的输入,然后关闭窗口,最后再打开另一个窗口来显示输入的文本。老实说,我对此很陌生,但通过我的先验知识和猜测,我尝试修改代码以满足我的期望。
import Tkinter as tk
global passtext
class application(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.textbox = tk.Text(self)
self.textbox.pack()
self.submitbutton = tk.Button(self, text="OK", command=self.showinputtext)
self.submitbutton.pack()
self.mainloop()
def showinputtext(self):
self.thetext = self.textbox.get("1.0", "end-1c")
print "You typed:", self.thetext
self.destroy()
class showtext(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.setthetext = tk.StringVar()
self.setthetext.set(passtext)
self.showthetext = tk.Label(self, textvariable=self.setthetext)
self.showthetext.pack()
self.submitbutton = tk.Button(self, text="OK", command=self.destroy)
self.submitbutton.pack()
self.mainloop()
# Launch the GUI
app = application()
# Access the entered text after closing the GUI
passtext = app.thetext
text = showtext()
我的英语有时会听不懂,但这个问题得到了回答。非常感谢你。
您的代码中有两个主要问题:
showinputtext
函数中,您想要访问 GUI 的元素,但它们未在函数范围内定义。tk.Text
小部件的内容时,该.get()
方法采用 2 个参数(请参阅此链接)。要解决第一个问题,最好将您的应用程序定义为一个类,内部函数将类实例self
作为输入参数,以便可以在该函数内调用应用程序小部件。
代码:
import Tkinter as tk
class application(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.textbox = tk.Text(self)
self.textbox.pack()
self.submitbutton = tk.Button(self, text="OK", command=self.showinputtext)
self.submitbutton.pack()
self.mainloop()
def showinputtext(self):
self.thetext = self.textbox.get("1.0", "end-1c")
print "You typed:", self.thetext
self.destroy()
# Launch the GUI
app = application()
# Access the entered text after closing the GUI
print "you entered:", app.thetext
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句