NameError:未定义全局名称“text”

时间:2017-03-10 04:24:43

标签: python tkinter

我有一个python代码片段,使用caesar密文将Mac地址转换为另一个代码:代码如下:

import uuid
def getmac():
  mac_num = hex(uuid.getnode()).replace('0x', '').upper()
  mac = ''.join(mac_num[i : i + 2] for i in range(0, 11, 2))
  return mac

plaintext = getmac()
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
key = 1
cipher = ''

for c in plaintext:
    if c in alphabet:
      cipher += alphabet[(alphabet.index(c) + key +3)%(len(alphabet))]
print('Code:' + cipher)

这适用于将代码输出到Python shell,但是当我使用TKinter库编辑相同的代码时,我会得到连接和其他错误,TKinter lib中使用的代码如下所示: 在这个片段中,程序的功能是相同的,但是我只想从用户输入mac地址,当他点击提交时,代码会提示给他:

import uuid
from Tkinter import *

root = Tk()

root.title("Code Generator")
root.geometry("250x200+200+100")
root.resizable(width=False, height=False)
cipher = ''


Label(root, text='Mac Address:').grid(row=0, sticky=W, padx=4)
Entry(root).grid(row=0, column=1, sticky=E, pady=4)

Label(root, text="Code:").grid(row=1, sticky=W, padx=4)
hlbl = Label(root, text=cipher,  width=20)
hlbl.grid(row=0, column=2, sticky=E, pady=4)


def get_it():
 alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  for c in text:
    if c in alphabet:
      cipher += alphabet[(alphabet.index(c) + key + 2) % (len(alphabet))]

Button(root, text="Submit", command=get_it).grid(row=2, column=1)
root.mainloop()

当我运行程序时,我得到了这个:
enter image description here
当我输入随机文本并单击提交时,我得到:
enter image description here
我应该做些什么改变?

1 个答案:

答案 0 :(得分:2)

首先,您需要为tkinter Entry命名,以便稍后引用,然后使用get方法获取Entry文字。

以下是修改后的代码;

import uuid
from Tkinter import *

root = Tk()

root.title("Code Generator")
root.geometry("250x200+200+100")
root.resizable(width=False, height=False)
key = 1
cipher = ''

label_text = StringVar()
#label_text.set(cipher)


Label(root, text='Mac Address:').grid(row=0, sticky=W, padx=4)
entry = Entry(root)
entry.grid(row=0, column=1, sticky=E, pady=4)

Label(root, text="Code:").grid(row=1, sticky=W, padx=4)
hlbl = Label(root, textvariable=label_text,  width=20)
hlbl.grid(row=1, column=1, sticky=E, pady=4)


def get_it():
    global key, cipher
    alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    text =  entry.get() # get contents of entry
    for c in text:
        if c in alphabet:
            cipher += alphabet[(alphabet.index(c) + key + 2) % (len(alphabet))]
    label_text.set(cipher)

Button(root, text="Submit", command=get_it).grid(row=2, column=1)
root.mainloop()