1

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.

1
  • 3
    That's not all of your code. What you've posted won't run. But it looks like you're trying to hash the contents of the Entry before the user has a chance to enter a string into it. Commented Oct 4, 2018 at 11:43

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

scantxt.bind("<Return>", hash_entry) with this I'm getting "AttributeError: 'NoneType' object has no attribute 'bind'".
@KartikA That means that in your code scantxt is None, not the Entry widget. Did you read the last section of my answer carefully?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.