【问题标题】:Want to use a Tkinter button for string input, then closing the button window and continue on想要使用 Tkinter 按钮进行字符串输入,然后关闭按钮窗口并继续
【发布时间】:2012-07-06 09:04:18
【问题描述】:

这似乎应该非常容易做到,但我正在努力。编程不是我的主要背景,所以我缺乏很多基础知识,但我正在努力学习。

我正在处理的问题是我想使用 Tkinter 按钮来显示按钮列表(目前只有一个),当按下其中一个按钮时,它将来自所述按钮的文本输入到字符串变量中,关闭按钮窗口,然后继续执行代码。

这是我为这部分准备的内容:

    root = tk.Tk()

    def data(name):
       global query 
       query = name


    B = tk.Button(root, text ='LogID', command = data('LogID'))

    B.pack()
    root.mainloop()

    print query

如果这看起来有点混乱或草率,那是因为它是。

本节之前有代码,本节之后有代码。我希望在按下按钮时关闭窗口(root.destroy())并让代码从“查询”打印文本,所以我知道它已将值传递给它。

当我运行它时,它挂在 root.mainloop() 部分,或者似乎挂起。老实说,我并不完全理解代码中的作用,我只知道它需要它。

【问题讨论】:

  • 尝试使用command=lambda x="LogID":data(x),你应该没事:)
  • 谢谢,我自己也在玩它,得到了一些非常接近它的东西。我发现之前对 Tkinter 的调用搞砸了。

标签: python button window tkinter


【解决方案1】:

因为我看到您已经在使用全局变量,
我将用一个
的例子来回答你的问题 如何使您的应用程序成为 Tkinter.Tk(python 3 中的 tkinter.Tk)的子类。

import Tkinter as tk

class Application(tk.Tk):

    def __init__(self):
        tk.Tk.__init__(self)
        self.title('Hello world!')
        self.data = None

        self.helloButton = tk.Button(self, width=12, text='Hello',
                    command=lambda x='hi': self.say_hi(x))
        self.helloButton.grid(row=0, column=1, padx=8, pady=8)

    def say_hi(self, x):
        self.data = x
        self.withdraw()
        self.secondWin = tk.Toplevel(self)
        self.secondWin.grid()
        self.output = tk.Entry(self.secondWin)
        self.output.insert(0, x)
        self.output.grid()
        self.quitButton = tk.Button(self.secondWin, text='Quit', bg='tan',
                                    command=self.close_app)
        self.quitButton.grid()

    def close_app(self):
        self.destroy()

app = Application()
app.mainloop()

变量 self.data 可以被类的任何方法使用;
因此,您不必使用 global 关键字。
mainloop 使您的 tkinter 应用程序保持“运行”并处理事件。
请注意,我没有破坏第一个窗口,而是使用withdraw 方法将其隐藏。
这只是您可能感兴趣的另一个选项。您可以使用deiconify 使其可见(更多信息here)。第二个窗口是 Toplevel 小部件,您可以使用它来创建辅助窗口。

我写了一个更有教育意义的例子,可以在here找到。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 2018-12-31
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 2014-04-07
    • 1970-01-01
    相关资源
    最近更新 更多