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

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.

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.

Related

display not changing despite variables being changed on tkinter

I want to write a program where after a user enters text and clicks a button, the text becomes a label and the button text is changed. My code is:
# Imports
import os, sys
import tkinter
"""
Tkinter program 1
text box + button + label
"""
# Button Entry
def enter(inputtedinfo, randvar, EnterMessage):
randvar = inputtedinfo.get()
EnterMessage = "Submitted!"
# Main Function
def main():
something = tkinter.Tk()
something.title("My First Tkinter Window")
something.geometry("600x400")
randvar = ""
EnterMessage = "Enter"
inputtedinfo = tkinter.StringVar()
userLabel = tkinter.Label(something, text = randvar)
userEntry = tkinter.Entry(something, textvariable = inputtedinfo)
userButton = tkinter.Button(something, text = EnterMessage, command = enter(inputtedinfo, randvar, EnterMessage))
userEntry.grid(row=0,column=0)
userLabel.grid(row=0,column=1)
userButton.grid(row=0,column=2)
something.mainloop()
sys.exit(0)
if(__name__ == "__main__"):
main()
The user input works, but clicking the button does nothing despite the fact that it is supposed to change the variables for the button and label displays. Did I mess up somewhere?
The command argument takes the name of a function. If you write the complete call with arguments, it's not the name of the function but whatever is returned by this exact function call. So, your button will not work. It will have the command None.
In order to do what you want to do, you have to make the StringVar()s accessible to the function you are calling. So, you can both get the contents of the entry and change the values of the button and the label. To do this, best add the string variables and the widgets as attributes to the toplevel you already created (something). So, they stay available to all functions and you can get and change information:
# Button Entry
def enter():
something.randvar.set(something.inputtedinfo.get())
something.userButton["text"] = "Submitted!"
# Main Function
def main():
global something
something = tkinter.Tk()
something.title("My First Tkinter Window")
something.geometry("600x400")
something.randvar = tkinter.StringVar()
something.randvar.set("")
EnterMessage = "Enter"
something.inputtedinfo = tkinter.StringVar()
userLabel = tkinter.Label(something, textvariable = something.randvar)
something.userEntry = tkinter.Entry(something, textvariable = something.inputtedinfo)
something.userButton = tkinter.Button(something, text = EnterMessage, command = enter)
something.userEntry.grid(row=0,column=0)
userLabel.grid(row=0,column=1)
something.userButton.grid(row=0,column=2)
something.mainloop()
if(__name__ == "__main__"):
main()
There are few issues in your code:
assign string to textvariable, should use StringVar instead
command=enter(...) will execute enter(...) immediately and then assign None to command option, should use lambda instead
updating strings inside enter() does not automatically update the label and the button, should use .set() on the StirngVar instead
Below is modified code:
def enter(inputtedinfo, randvar, EnterMessage):
# used .set() to update StringVar
randvar.set(inputtedinfo.get())
EnterMessage.set("Submitted!")
def main():
something = tkinter.Tk()
something.title("My First Tkinter Window")
something.geometry("600x400")
randvar = tkinter.StringVar() # changed to StringVar()
EnterMessage = tkinter.StringVar(value="Enter") # changed to StringVar()
inputtedinfo = tkinter.StringVar()
userLabel = tkinter.Label(something, textvariable=randvar) # used textvariable instead of text option
userEntry = tkinter.Entry(something, textvariable=inputtedinfo)
userButton = tkinter.Button(something, textvariable=EnterMessage, command=lambda: enter(inputtedinfo, randvar, EnterMessage))
userEntry.grid(row=0,column=0)
userLabel.grid(row=0,column=1)
userButton.grid(row=0,column=2)
something.mainloop()

delete buttons defined in other function

I'm trying to get a button to dissapear when you click it, and other buttons to appear. Then when the "back" button is clicked, I want the newer buttons to dissapear again, and the original button to appear again.
The problem is that I don't know how to make a function retrieve information from another function. If I try to do anything to the search_button in the search(event) function, the search_button is not defined because it was only defined in the main() function.
import tkinter as tk
window = tk.Tk()
def search(event):
#insert "delete search_button" logic here
easy_button = tk.Button(window, text = "Easy")
easy_button.bind("<Button-1>", easy_search)
easy_button.pack()
back_button = tk.Button(window, text = "Back")
back_button.bind("<Button-1>", back_button1) #had to put 1 on end here. It seems back_button is predefined as an object
back_button.pack()
def easy_search(event):
#does a bunch of stuff that doesn't matter for this question
pass
def back_button1(event):
#this should delete easy_button and reinitiate search_button
pass
def main():
search_button = tk.Button(window, text = "Search")
search_button.bind("<Button-1>", search)
search_button.pack()
main()
window.mainloop()
The easiest way is to make everything into a class, in which all your functions could share the same self namespace. And that if you want to bind the button pressed with another function, use 'command' instead, unless you're actually using the event.
That will come together to this:
import tkinter as tk
window = tk.Tk()
class Search:
def __init__(self):
self.search_button = tk.Button(window, text = "Search")
self.search_button['command'] = self.search
self.search_button.pack()
def search(self):
self.search_button.pack_forget() # or .destroy() if you're never going to use it again
self.easy_button = tk.Button(window, text = "Easy")
self.easy_button['command'] = self.easy_search
self.easy_button.pack()
self.back_button = tk.Button(window, text = "Back")
self.back_button['command'] = self.back_button1
self.back_button.pack()
def easy_search(self):
#does a bunch of stuff that doesn't matter for this question
pass
def back_button1(self):
#this should delete easy_button and reinitiate search_button
pass
widgets = Search()
window.mainloop()
There you can call the widget's destroy or pack_forget command.

How to make a pop up button (Python)

How would I make it it so a pop up box (If you have better name for it comment below) appear asking you a question. It would have one button saying I agree and another saying I disagree.
Here’s a simple one I suppose:
import tkinter as tk
root = tk.Tk()
questionsAsked = []
def yes():
#do stuff if the user says yes
pass
def no():
#do stuff if the user says no
pass
def modal(question):
if question in questionsAsked:
return False
questionsAsked.append(question)
label = tk.Label(root, text=question)
bYes = tk.Button(root, text="Yes", command=yes)
bNo = tk.Button(root, text="No", command=no)
for el in [label, bYes, bNo]:
el.pack()
modal("Do you want to continue?")
root.mainloop()

Label variables for exchange rate calculator [duplicate]

I am having trouble with using a key binding to change the value of a label or any parameter.
This is my code:
from tkinter import*
class MyGUI:
def __init__(self):
self.__mainWindow = Tk()
#self.fram1 = Frame(self.__mainWindow)
self.labelText = 'Enter amount to deposit'
self.depositLabel = Label(self.__mainWindow, text = self.labelText)
self.depositEntry = Entry(self.__mainWindow, width = 10)
self.depositEntry.bind('<Return>', self.depositCallBack)
self.depositLabel.pack()
self.depositEntry.pack()
mainloop()
def depositCallBack(self,event):
self.labelText = 'change the value'
print(self.labelText)
myGUI = MyGUI()
When I run this, I click the entrybox and hit enter, hoping that the label will change value to 'change the value'. However, while it does print that text, the label remains unchanged.
From looking at other questions on similar problems and issues, I have figured how to work with some of this outside a class, but I'm having some difficulties with doing it inside a class.
self.labelText = 'change the value'
The above sentence makes labelText change the value, but not change depositLabel's text.
To change depositLabel's text, use one of following setences:
self.depositLabel['text'] = 'change the value'
OR
self.depositLabel.config(text='change the value')
You can also define a textvariable when creating the Label, and change the textvariable to update the text in the label.
Here's an example:
labelText = StringVar()
depositLabel = Label(self, textvariable=labelText)
depositLabel.grid()
def updateDepositLabel(txt) # you may have to use *args in some cases
labelText.set(txt)
There's no need to update the text in depositLabel manually. Tk does that for you.
Use the config method to change the value of the label:
top = Tk()
l = Label(top)
l.pack()
l.config(text = "Hello World", width = "50")
Here is another one, I think. Just for reference.
Let's set a variable to be an instantance of class StringVar
If you program Tk using the Tcl language, you can ask the system to let you know when a variable is changed. The Tk toolkit can use this feature, called tracing, to update certain widgets when an associated variable is modified.
There’s no way to track changes to Python variables, but Tkinter
allows you to create variable wrappers that can be used wherever Tk
can use a traced Tcl variable.
text = StringVar()
self.depositLabel = Label(self.__mainWindow, text = self.labelText, textvariable = text)
# ^^^^^^^^^^^^^^^^^^^
def depositCallBack(self,event):
text.set('change the value')
I made a small tkinter application which is sets the label after button clicked
#!/usr/bin/env python
from Tkinter import *
from tkFileDialog import askopenfilename
from tkFileDialog import askdirectory
class Application:
def __init__(self, master):
frame = Frame(master,width=200,height=200)
frame.pack()
self.log_file_btn = Button(frame, text="Select Log File", command=self.selectLogFile,width=25).grid(row=0)
self.image_folder_btn = Button(frame, text="Select Image Folder", command=self.selectImageFile,width=25).grid(row=1)
self.quite_button = Button(frame, text="QUIT", fg="red", command=frame.quit,width=25).grid(row=5)
self.logFilePath =StringVar()
self.imageFilePath = StringVar()
self.labelFolder = Label(frame,textvariable=self.logFilePath).grid(row=0,column=1)
self.labelImageFile = Label(frame,textvariable = self.imageFilePath).grid(row = 1,column=1)
def selectLogFile(self):
filename = askopenfilename()
self.logFilePath.set(filename)
def selectImageFile(self):
imageFolder = askdirectory()
self.imageFilePath.set(imageFolder)
root = Tk()
root.title("Geo Tagging")
root.geometry("600x100")
app = Application(root)
root.mainloop()
There are many ways to tackle a problem like this. There are many ways to do this. I'm going to give you the most simple solution to this question I know. When changing the text of a label or any kind of wiget really. I would do it like this.
Name_Of_Label["text"] = "Your New Text"
So when I apply this knowledge to your code. It would look something like this.
from tkinter import*
class MyGUI:
def __init__(self):
self.__mainWindow = Tk()
#self.fram1 = Frame(self.__mainWindow)
self.labelText = 'Enter amount to deposit'
self.depositLabel = Label(self.__mainWindow, text = self.labelText)
self.depositEntry = Entry(self.__mainWindow, width = 10)
self.depositEntry.bind('<Return>', self.depositCallBack)
self.depositLabel.pack()
self.depositEntry.pack()
mainloop()
def depositCallBack(self,event):
self.labelText["text"] = 'change the value'
print(self.labelText)
myGUI = MyGUI()
If this helps please let me know!

How do you close a tkinter window in another function?

I want a button in my window to open a new window and close the previous one. Is it possible to have one button do both of these? I've tried in the following code, but it hasn't worked, just told me that window is not defined:
import tkinter
def window1():
window = tkinter.Tk()
tkinter.Button(window, text = "Next", command = window2).pack()
window.mainloop()
def window2():
window.destroy() #This is where the error is
menu = tkinter.Tk()
etc, etc, etc
window1()
First, you need to return the window object from the first function:
def window1():
window = tkinter.Tk()
tkinter.Button(window, text = "Next", command = lambda: window2(window)).pack()
window.mainloop()
return window
Then, you need to pass the window as an argument to your function:
def window2(window):
window.destroy()
menu = tkinter.Tk()
And then call window1 with:
window = window1()
and click the button to destroy it and do the rest
This is an example using Toplevels, which is usually a better choice than creating, destroying, re-creating Tk() instances. The unique Toplevel ID is passed to the close_it function using partial(). You would, of course, combine them or have the close function call the open function.
try:
import Tkinter as tk ## Python 2.x
except ImportError:
import tkinter as tk ## Python 3.x
from functools import partial
class OpenToplevels():
""" open and close additional Toplevels with a button
"""
def __init__(self):
self.root = tk.Tk()
self.button_ctr=0
but=tk.Button(self.root, text="Open a Toplevel",
command=self.open_another)
but.grid(row=0, column=0)
tk.Button(self.root, text="Exit Tkinter", bg="red",
command=self.root.quit).grid(row=1, column=0, sticky="we")
self.root.mainloop()
def close_it(self, id):
id.destroy()
def open_another(self):
self.button_ctr += 1
id = tk.Toplevel(self.root)
id.title("Toplevel #%d" % (self.button_ctr))
tk.Button(id, text="Close Toplevel #%d" % (self.button_ctr),
command=partial(self.close_it, id),
bg="orange", width=20).grid(row=1, column=0)
Ot=OpenToplevels()
Yes. Is possible. But you'll need to def that:
def window1:
blablabla
blablabla
def window2:
window2.destroy() <-- Here where the error was
How you noticed, put your name of window what you want Destroy and it will work!
using Python3
You could use a "global" such as:
root = Tk()
root.title('This is the root window')
def window_create():
global window_one
window_one = Tk()
window_one.title('This is window 1')
Then, from any function (or elsewhere) when you want to destroy window_one, do:
def window_destroyer():
window_one.destroy()
You could call your window_destroyer function from a button anywhere such as root which the example shows:
kill_window_btn = Button(root, text="Destroy", command=window_destroyer).pack()
Of course, follow your own naming conventions. :)
It seems to me, just 'global window_one' would solve it.

Categories