从另一个函数 A 关闭 Tkinter GUI,并将 Tkinter 变量传递给函数 A



这个问题是关于在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()

我的英语有时听不懂,但这个问题得到了回答。谢谢。

代码中有 2 个主要问题:

  • 首先,在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

最新更新