如何获取Tkinter Entry输入值供跨窗口函数使用
问题原因
你传值失败是代码里三个典型Tkinter写法错误导致的:
- 你写
cipherEntry = Entry(...).pack()时,.pack()方法返回值是None,变量cipherEntry根本没有保存输入框组件实例,后续调用.get()必然报错 cipherEntry是openCipher()函数内的局部变量,定义在全局的ciphering()函数默认无法访问到这个变量- 你用
list()把输入字符串转成字符列表后,还对列表对象调用.get()方法,Python原生列表没有这个方法,运行会直接抛出属性错误
注意:所有Tkinter组件只要链式调用pack/grid/place布局方法,变量拿到的永远是None,这是新手最容易踩的固定坑
可行实现方案
按以下三点修改即可正常传值:
- 所有Tkinter组件先单独实例化赋值给变量,再单独调用布局方法,不要链式调用
- 给子窗口内的Cipher按钮绑定命令时,用lambda表达式把cipherEntry输入框实例作为参数传入ciphering函数
- 修正ciphering函数内的逻辑:拿到输入内容转成字符列表后,直接用原始输入字符串做界面展示,不要对列表调用get方法
修正后的完整可运行代码如下:
from tkinter import * from PIL import ImageTk,Image from tkinter import messagebox root = Tk() root.eval("tk::PlaceWindow . center") root.title('d3cryptt') def openCipher(): cipher = Toplevel() cipher.title("decryptt - CIPHER") # 先创建组件赋值给变量,再单独调用pack cipherLabel = Label(cipher, text="cipher") cipherLabel.pack() cipherEntry = Entry(cipher, width=20, borderwidth=5) cipherEntry.pack() quitButton = Button(cipher, text="Exit Cipher", padx=10, pady=5, command=cipher.destroy) quitButton.pack() # 用lambda传参把cipherEntry传入ciphering cipherButton = Button(cipher, text="Cipher", padx=10, pady=5, command=lambda: ciphering(cipherEntry)) cipherButton.pack() def openDecipher(): decipher = Toplevel() decipher.title("decryptt - DECIPHER") decipherLabel = Label(decipher, text="decipher") decipherLabel.pack() quitButton = Button(decipher, text="Exit Decipher", padx=10, pady=5, command=decipher.destroy) quitButton.pack() def ciphering(cipherEntry): # 先获取输入框的字符串内容 input_str = cipherEntry.get() # 拆分为单个字符的列表 seperatedWord = list(input_str) # 直接用原始字符串展示,不要对列表调get cipherLabeling = Label(root, text = f"You have inputted {input_str}, split result: {seperatedWord}") cipherLabeling.pack() appLogo = ImageTk.PhotoImage(Image.open("d3cryptt_logo_resized.png")) appLogoLabel = Label(image=appLogo) appLogoLabel.grid(row=0, column=0, columnspan=2) cipherButton = Button(root, text=" Cipher ", padx=40, pady=20, command=openCipher) cipherButton.grid(row=1, column=0) decipherButton = Button(root, text="Decipher", padx=40, pady=20, command=openDecipher) decipherButton.grid(row=1, column=1) spacer1 = Label(root, text=" ", padx=10, pady=1) spacer1.grid(row=4, column=1) quitButton = Button(root, text="Exit d3cryptt", padx=10, pady=5, command=root.quit) quitButton.grid(row=5, column=0, columnspan=2) spacer2 = Label(root, text=" ", padx=10, pady=1) spacer2.grid(row=6, column=1) root.mainloop()
额外说明
如果后续需要在ciphering里对拆分后的字符列表做加解密逻辑,直接操作seperatedWord变量即可,不需要额外再调用取值方法。
内容的提问来源于stack exchange,提问作者HarrisonT
相关产品推荐
相关产品推荐

