Reputation: 13
I wanted to convert StringVar into String in Python.
Aim : String entered in Entry field (tkinter) must be converted to String and then encoded to get the hash of it.
Below is my code:
txt1 = StringVar()
scantxt = ttk.Entry(win, textvariable = txt1).pack()
txt1 = str(txt1.get()).encode()
sha256 = hashlib.sha256(txt1)
estr = sha256.hexdigest()
The result I'm getting is hash of blank text.
I don't know where I'm going wrong. Please assist.
Thank you for anticipated help.
Upvotes: 1
Views: 10610
Reputation: 55499
Usually, a GUI program sits in a loop, waiting for events to respond to. The code fragment you posted doesn't do that.
You don't need a StringVar for this task. You can give an Entry widget a StringVar, but it doesn't need it. You can fetch its text contents directly using its .get
method. But you do need a way to tell your program when it should fetch and process that text, and what it should do with it.
There are various ways to do that with an Entry widget: if you need to, your code can be notified of every change that happens to the Entry text. We don't need that here, we can ask Tkinter to run a function when the user hits the Return key. We can do that using the widget's .bind
method.
import tkinter as tk
from tkinter import ttk
import hashlib
win = tk.Tk()
scantxt = ttk.Entry(win)
scantxt.pack()
def hash_entry(event):
txt1 = scantxt.get()
sha256 = hashlib.sha256(txt1.encode())
estr = sha256.hexdigest()
print(txt1, estr)
scantxt.bind("<Return>", hash_entry)
win.mainloop()
You'll notice that I got rid of
scantxt = ttk.Entry(win, textvariable = txt1).pack()
The .pack
method (and the .grid
& .place
methods) return None
, so the above statement binds None
to the name scantxt
, it does not save a reference to the Entry widget.
Upvotes: 3