Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
681 views
in Technique[技术] by (71.8m points)

python - Using the variable from entry/button in another function in Tkinter

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Structure the program using class.

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

You can access the input using prompt.my_entry later.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...