【问题标题】:Using the variable from entry/button in another function in Tkinter在 Tkinter 的另一个函数中使用条目/按钮中的变量
【发布时间】:2014-01-13 07:55:06
【问题描述】:

当我按下按钮时,我希望它获得 Entry 并 - 为将来的事情 - 在另一个功能中使用它。

import tkinter

def ButtonAction():
    MyEntry = ent.get() #this is the variable I wanna use in another function

den = tkinter.Tk()
den.title("Widget Example")

lbl = tkinter.Label(den, text="Write Something")
ent = tkinter.Entry(den)
btn = tkinter.Button(den, text="Get That Something", command = ButtonAction )

lbl.pack()
ent.pack()
btn.pack()

den.mainloop()

print MyEntry #something like this maybe. That's for just example

我会用这个东西作为搜索工具。将出现条目窗口,从那里获取该“条目”并在以下文件中搜索:

if MyEntry in files:
 #do smth

我知道我可以使用全局变量来解决这个问题,但根据我的阅读,不建议将它作为第一个解决方案。

【问题讨论】:

    标签: python python-3.x tkinter


    【解决方案1】:

    使用类构建程序。

    import tkinter
    
    class Prompt:
        def button_action(self):
            self.my_entry = self.ent.get() #this is the variable I wanna use in another function
    
        def __init__(self, den):
            self.lbl = tkinter.Label(den, text="Write Something")
            self.ent = tkinter.Entry(den)
            self.btn = tkinter.Button(den, text="Get That Something", command=self.button_action)
            self.lbl.pack()
            self.ent.pack()
            self.btn.pack()
    
    den = tkinter.Tk()
    den.title("Widget Example")
    prompt = Prompt(den)
    den.mainloop()
    

    您可以稍后使用prompt.my_entry 访问输入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-15
      • 2022-01-11
      • 2021-05-31
      • 2019-07-21
      • 1970-01-01
      • 2013-09-17
      相关资源
      最近更新 更多