首页 > 解决方案 > 如何将输入字段值传递给函数

问题描述

我正在尝试使用tkinteron制作一个基于 GUI 的加密程序python3。这里的一个选项是加密图像,现在有一个输入字段,用户将在其中输入模式,1 表示 RGB,0 表示灰度。现在我正在尝试将该输入字段值传递给加密和解密函数,该函数将在按下相应按钮时执行。但是在将值传递给函数时出现错误。编写按钮和输入字段的脚本,如下:

global mode

def getvalue():
    mode =int(mode_txt.get()) 
    return mode


image_window = Tk()
image_window.geometry ( '350x200' )
image_window.title ('Image Cryptography')
lbl1 = Label(image_window, text = "Select mode(0 for greyscale/ 1 for RGB): " ).place( x=20, y=40 )
mode_txt = IntVar
mode_txt = Entry(image_window, width = 4) #the entry field 
mode_txt.place(x= 300, y=40)
mode_txt.bind('<Return>', getvalue)
mode_txt.pack() 

现在我通过mode这样的:

def encrypt():

    mode = getvalue()   
    if(mode == 0): #greyscale
    #some code#

按钮是这样的:

btn_decrypt = Button( image_window, text = "Image Decryption", command = decrypt)
btn_decrypt.place( x=20, y=100 )
btn_encrypt = Button( image_window, text = "Image Encryption", command = encrypt)
btn_encrypt.place( x=200, y=100 )
btn_exit = Button( image_window, text = "Go Back" , command = goback).place( x=140, y=150 )
image_window.mainloop()

我得到的错误是:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib64/python3.7/tkinter/__init__.py", line 1705, in __call__
    return self.func(*args)
  File "image1.py", line 98, in decrypt
    if(mode == 0):
NameError: name 'mode' is not defined

我不知道我哪里出错了?任何帮助将不胜感激。谢谢你。

标签: pythonpython-3.xtkinterparameter-passing

解决方案


推荐阅读