简体   繁体   English

python中的类型转换(将StringVar转换为String)

[英]Type conversion in python (StringVar to String)

I wanted to convert StringVar into String in Python. 我想将StringVar转换为Python中的String

Aim : String entered in Entry field (tkinter) must be converted to String and then encoded to get the hash of it. 目的 :必须将在“输入”字段(tkinter)中输入的字符串转换为字符串,然后进行编码以获取其哈希值。

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. 感谢您的帮助。

Usually, a GUI program sits in a loop, waiting for events to respond to. 通常,GUI程序处于循环中,等待事件响应。 The code fragment you posted doesn't do that. 您发布的代码片段无法做到这一点。

You don't need a StringVar for this task. 您不需要StringVar即可完成此任务。 You can give an Entry widget a StringVar, but it doesn't need it. 您可以为Entry小部件提供StringVar,但不需要它。 You can fetch its text contents directly using its .get method. 您可以使用.get方法直接获取其文本内容。 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. 有多种方法可以使用Entry小部件执行此操作:如果需要,可以将Entry文本发生的每次更改通知您的代码。 We don't need that here, we can ask Tkinter to run a function when the user hits the Return key. 我们不需要这里,我们可以要求Tkinter在用户按下Return键时运行一个函数。 We can do that using the widget's .bind method. 我们可以使用小部件的.bind方法做到这一点。

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. .pack方法(和.grid.place方法)返回None ,所以上面的语句结合None以名scantxt ,它保存到输入构件的参考。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM