How to reset StringVar in tkinter - python

I am currently working on a calculator and I was coding the C Button (C button is the button which erases the current operation) however, My idea was to make the C Button return all Variables used during the operation to their starting state so we can start a new operation after pressing C. The problem is there is something called StringVar() in Tkinter that I used after reading an answer on StackOverflow. It is used to update the label every time I hit a new Button. it works but when trying to return it to its normal state when pressing the C button it doesn't work. They are still the same. so how can I reset the StringVar?
solution: Turns out I didn't assign the global variables used in the function, but any way to reset the stringVar you can just do this : (variable name).set("")

It should be variableName.set("")
s = StringVar()
# here getting textvariable
value = s.get()
print(value) # input value
s.set("") # reset it
Edit: After below comment, I am adding this structure to show how to keep desired item clean
# getting input
sFaculty = StringVar()
combo = ttk.Combobox(tab1, ..., textvariable=sFaculty, ...)
# assing it to function
Button(tab1, text="Insert", command=lambda: guiActions.insertStudent(..., sFaculty, ...))
# process and clean in a function
def insertStudent(..., faculty, ...):
# process here
# cleaning after insert
faculty.set("")

Related

Python 3, Keyboard module -How to stop the default action when adding a hotkey (workaround found)

I'm trying to overwrite an existing keyboard function on the enter key with a custom hotkey. The problem is, I cannot stop the default action from occurring also. Worse yet, it occurs after the custom action, so I don't have the chance to retroactively correct it as well.
Here are the relevant parts of the code:
from tkinter import *
from tkinter import ttk
from keyboard import *
root = Tk()
root.geometry('400x300')
'''This is the problematic function called by the hotkey'''
def entr_key(text):
'''Enter key results in printing of the line to the right of cursor'''
curs_pos = text.index(INSERT)
right_hand = text.get(curs_pos,END)
right_hand = right_hand.split('\n')[:1] #lines -> strs in a list, selects the first
print (right_hand)
return
'''THIS IS THE MAIN WIDGET FOR THIS FRAME'''
text_view = ttk.Frame(root, padding=10)
text_view.grid()
text_box = Text(text_view, width=45, wrap=WORD)
text_box.grid(column=0, row=1)
text_box.insert('1.0', 'This is a Text widget demo,\nThis text is aimed at testing the enter key function')
add_hotkey("enter", lambda: entr_key(text_box))
root.mainloop()
(I've changed up some variable names to be more understandable, apologies if I missed any but it's not the source of the problem!)
I've also (unsuccesfully) tried other ways of doing this, eg:
while True:
if is_pressed('enter'):
entr_key(text_box)
'''AND ALSO'''
on_press_key("enter", lambda x=None: entr_key(text_box))
Just to be clear, I don't want the default action of enter key moving the text to a new line.
I need either a way to "break" the key event so that only the custom action takes place, or a way for the custom action to occur after default action, so I can retroactively edit it out
EDIT!!!
I've found a workaround: at the start of entr_key() I call time.sleep(0.01). During this, the default action of the enter key occurs first, and I can retroactively edit it out when the custom function resumes. The delay is slight enough to not be noticeable at all.
But still, if anyone knows how to prevent the default action from occurring completely, I would really appreciate it.

If I created widgets in one function, how can I access them in another function using Python Tkinter?

this is my first project using Tkinter so please excuse me if the question is very simple to solve.
Depending on what option the user chooses from a dropdown, I call a function that creates and places certain widgets (e.g. an entry) on a frame. Then, when another button is pushed I want to access the text inside this entry. However, this seems to be giving me errors (saying that the widget is undefined) because I want to access a widget which I create when a function is called.
An obvious solution I see is to create all possible widgets I want to use outside the function, and only place them when the function is called. This seems quite sloppy and creates many more issues. Is there another fix?
Thanks in advance!
This is the function where I create and place the widgets on the frame.
def loadBook():
print("book is loaded")
#Authors
labelAuth1 = tk.Label(frame, text="Author 1 Name:")
entryAuth1 = tk.Entry(frame)
labelAuth1.place(relwidth=0.23, relheight=0.08, rely=0.1)
entryAuth1.place(relheight=0.08, relwidth=0.18, relx=0.3, rely=0.1)
This is a snippet of a function which uses input from the entry widget I created above:
def isBook():
if len(entryAuthSur1.get())==0:
pass
else:
bookString = ""
bookString += entryAuthSur1.get()
When the second function executes, I get a runtime error that entryAuthSur1 is not defined.
All variables inside functions are local. That means that it is deleted after the function call ends. As your variable (entryAuth1) wasn't global so it only existed inside the function and was deleted when the loadBook function ended. This is the working code:
import tkinter as tk
# Making a window for the widgets
root = tk.Tk()
def loadBook():
global entryAuth1 # make the entry global so all functions can access it
print("book is loaded")
#Authors
labelAuth1 = tk.Label(root, text="Author 1 Name:")
entryAuth1 = tk.Entry(root)
# I will check if the user presses the enter key to run the second function
entryAuth1.bind("<Return>", lambda e: isBook())
labelAuth1.pack()
entryAuth1.pack()
def isBook():
global entryAuth1 # make the entry global so all functions can access it
# Here you had `entryAuthSur1` but I guess it is the same as `entryAuth1`
if len(entryAuth1.get())==0:
pass
else:
bookString = ""
bookString += entryAuth1.get()
print(bookString) # I am going to print the result to the screen
# Call the first function
loadBook()
root.mainloop()

Python, Tkinter - Making get() dynamic

Below is some code that I'm testing with. In this code, I am able to create a window and have a Label on top and a Entry field on bottom. When I type in that entry field, I can dynamically change what's in the label. Now, I have included a function that is trying to evaluate a variable assigned to "tex", by storing what is predefined in the Entry widget. Which is "cat". This is picked up by:
tex = e.get()
I understand that get() is not changing dynamically as I change the text in the entry widget. So it cannot change to "dog" when I change the string in the entry widget. Is this possible? Here is the code:
from Tkinter import *
import time
root = Tk()
def change():
if tex == ("cat"):
time.sleep(0.5)
pass
else:
time.sleep(0.5)
e.delete(0, END)
e.insert(0, "dog")
v = StringVar()
e = Entry(root, textvariable=v)
e.insert(0, "cat")
e.pack(side=BOTTOM)
tex = e.get() #When text is defined with get(), it does not change
#dynamically with the entry widget
l = Label(root, textvariable=v)
l.pack(side=TOP)
change()
root.mainloop()
Any help would be appreciated.
To answer your specific question, no, there is no way for tex to magically keep updated when the entry widget changes. That feature is exactly why the textvariable attribute exists -- it causes the variable to always be updated with the value in the entry widget. If you need the data in another variable, you will have to call the .get() method.
That being said, you can set a trace on the variable, or a binding on the entry widget, and have it call code that can update tex to whatever you want when the entry widget changes.
For example, the following code shows how to have callback called whenever the value in the entry widget changes:
def callback(*args):
global tex
tex = e.get()
v.trace("w", callback)
For more information about what arguments are passed to the callback, see What are the arguments to Tkinter variable trace method callbacks?
All that being said, you have a couple of critical flaws in your code. First, you are creating the StringVar incorrectly. It needs to be v = StringVar() (note the trailing ()).
Also, you should never call sleep in the main thread of a GUI program. Read up on the after method if you want to execute some code after some time has elapsed.

Checking if the user presses 'Return' while selected in an Entry box Tkinter

I'm using Tkinter to create a GUI for a simple geometry calculator I'm creating.
Basically, what I have is an Entry box. What I want is for the program/GUI/system to detect when the user of the program hits the 'Enter' or 'return' key WHILE they are in the Entry box. When this is detected, I want the contents of the Entry box to be appended to a list I have defined earlier. I also want a simple label to be created on the GUI that displays the contents of the list (including the appended item(s)). Note that the list begins with nothing in it.
Here is my code so far:
from tkinter import *
#Window setup(ignore this)
app = Tk()
app.title('Geometry Calculator')
app.geometry('384x192+491+216')
app.iconbitmap('Geo.ico')
app.minsize(width=256, height=96)
app.maxsize(width=384, height=192)
app.configure(bg='WhiteSmoke')
#This is the emtry list...
PointList = []
#Here is where I define the variable that I will be appending to the list (which is the object of the Entry box below)
StrPoint = StringVar()
def list_add(event):
#I don't really know how the bind-checking works and how I would implement it; I want to check if the user hits enter while in the Entry box here
if event.char == '':
PointList.append(StrPoint)
e1 = Entry(textvariable=StrPoint).grid(row=0, column=0)
app.bind('<Return>', list_add)
mainloop()
I don't really know the proper way to check for 'Return' and then use it in an if statement.
I hope you understand what I'm trying to get help with, and I've looked all around for an explanation that I could understand with no success.
Instead of binding with the app just bind it with the Entry widget object,i.e,e1
from tkinter import *
#Window setup(ignore this)
app = Tk()
app.title('Geometry Calculator')
app.geometry('384x192+491+216')
app.iconbitmap('Geo.ico')
app.minsize(width=256, height=96)
app.maxsize(width=384, height=192)
app.configure(bg='WhiteSmoke')
#This is the emtry list...
PointList = []
#Here is where I define the variable that I will be appending to the list (which is the object of the Entry box below)
StrPoint = StringVar()
def list_add(event):
print ("hello")
#I don't really know how the bind-checking works and how I would implement it; I want to check if the user hits enter while in the Entry box here
if event.char == '':
PointList.append(StrPoint)
e1 = Entry(textvariable=StrPoint)
e1.grid(row=0, column=0)#use grid in next line,else it would return None
e1.bind('<Return>', list_add)# bind Entry
mainloop()
The solution is to set the binding on the widget itself. That way, the binding will only apply while focus is on that widget. And since you're binding on a specific key, you don't need to check for the value later. You know the user pressed return, because that's the only thing that will cause the binding to fire.
...
e1.bind('<Return>', list_add)
...
You have another problem in that your list_add function needs to call the get method of the variable rather than accessing the variable directly. However, since you aren't using any of the special features of a StringVar, you really don't need it -- it's just one more thing you have to manage.
Here's how to do it without the StringVar:
def list_add(event):
PointLit.append(e1.get())
...
e1 = Entry(app)
e1.grid(row=0, column=0)
e1.bind('<Return>', list_add)
Note that you need to create the widget and lay out the widget in two steps. Doing it the way you did it (e1=Entry(...).grid(...) will cause e1 to be None since that is what .grid(...) returns.

More on passing arguments to tkinter button command

I have a number of test files in a single directory. I'm trying to write a GUI to allow me to select and run one of them.
So, I have a loop that scans the directory and creates buttons:
for fnm in glob.glob ('Run*.py'):
tstName = fnm[3:-3] # Discard fixed part of filename
btn = Button (self, text=tstName,
command=lambda: self.test(tstName))
btn.grid (row=rowNum, column=0, pady=2)
rowNum += 1
This creates my GUI correctly, with buttons labelled say, A and B but when I press on the button labelled A it passes B to the test method.
I've looked around and found this question How can I pass arguments to Tkinter button's callback command? but the answer doesn't go on to use the same variable name, with a different value, to configure another widget. (In fact, by tying the variable name to the widget name it almost implies that the technique won't work in this case, as I've found.)
I'm very new to Python, but am quite familiar with creating this kind of GUI using Tcl/TK and I recognise this problem - the value of tstName is being passed when I press the button, but I want it to pass the value the variable had when I created it. I know how I'd fix that in Tcl/Tk - I'd define a command string using [list] at creation time which would capture the value of the variable.
How do I do the same in Python?
You need to bind the current value of tstName at the time you define the button. The way you're doing it, the value of tstName will whatever it is at the time you press the button.
To bind the value at the time that you create the button, use the value of tstName as the default value of a keyword parameter to the lambda, like so:
btn = Button(..., command=lambda t=tstName: self.test(t))

Categories

Resources