想用Tkinter按钮输入字符串,然后关闭按钮窗口并继续

2024-09-30 01:23:27 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我要处理的问题是我想使用一个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

如果这看起来有点杂乱无章,那是因为它确实如此。在

这部分前面有代码,后面有代码。我想把窗户关上(根目录。销毁())当按下按钮时,代码将从“query”打印文本,因此我知道它已将值传递给它。在

当我运行它时,它挂在根.mainloop()节,或似乎是。老实说,我不完全理解代码中的功能,我只知道它需要它。在


Tags: 代码name文本列表datatkinter编程root
1条回答
网友
1楼 · 发布于 2024-09-30 01:23:27

因为我看到您已经在使用全局变量,
我将用一个
如何使应用程序成为Tkinter.Tk.塔卡(tkinter.Tk.塔卡在python 3中)。在

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()

变量自我数据可以由您的类的任何方法使用;
因此,您不必使用global关键字。
mainloop使tkinter应用程序“运行”并处理事件。
请注意,我没有销毁第一个窗口,而是使用withdraw方法将其隐藏起来。
这只是你可能感兴趣的另一个选择。您可以使用deiconify使其可见(更多信息here)。第二个窗口是一个顶层小部件,您可以使用它来创建辅助窗口。在

我写了一个更有教育意义的例子here。在

相关问题 更多 >

    热门问题