在 Tkinter 的另一个函数中使用来自条目/按钮的变量 [英] Using the variable from entry/button in another function in Tkinter

查看:32
本文介绍了在 Tkinter 的另一个函数中使用来自条目/按钮的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I press the button, I want it to get the Entry and -for future things- use it in another function.

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

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

I will use this thing as a search tool. Entry window will appear, get that "entry" from there and search it in files like:

if MyEntry in files:
 #do smth

我知道我可以通过使用全局变量来解决这个问题,但据我所知,不建议将其作为第一个解决方案.

I know I can handle the problem with using globals but from what I've read it's not recommended as a first solution.

推荐答案

使用类构建程序.

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 访问输入.

You can access the input using prompt.my_entry later.

这篇关于在 Tkinter 的另一个函数中使用来自条目/按钮的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆