使用GUI Designer生成的Tkinter代码无法获取Entry组件返回值的技术问题
解决Tkinter按钮点击无法获取Entry输入值的问题
我一眼就看出问题出在哪了——你在__init__方法里刚创建完输入框就立刻调用了get(),这时候用户还没来得及输入任何内容,所以x和y从一开始就是空字符串,之后不管用户输入什么,这两个变量都不会自动更新。
核心问题分析
你现在的代码里:
x = GiveSource.get() #####This is wrong!##### y = GiveTarget.get() #####This is also wrong!#####
这两行是在App初始化时执行的,此时输入框是空的,所以x和y永远是空。而且你把GiveSource和GiveTarget定义成了__init__里的局部变量,之后在StartButton_command里也没法直接访问到这些输入框组件,自然没法获取最新的输入值。
修正后的代码
下面是修复好的版本,我标注了关键修改点:
import tkinter as tk import tkinter.font as tkFont import subprocess import os class App: def __init__(self, root): # 修改:把GiveSource变成实例属性self.GiveSource self.GiveSource=tk.Entry(root) self.GiveSource["borderwidth"] = "1px" ft = tkFont.Font(family='Times',size=10) self.GiveSource["font"] = ft self.GiveSource["fg"] = "#333333" self.GiveSource["justify"] = "left" self.GiveSource.place(x=110,y=50,width=328,height=30) # 删掉提前get值的代码,不需要全局变量x # 修改:把GiveTarget变成实例属性self.GiveTarget self.GiveTarget=tk.Entry(root) self.GiveTarget["borderwidth"] = "1px" ft = tkFont.Font(family='Times',size=10) self.GiveTarget["font"] = ft self.GiveTarget["fg"] = "#333333" self.GiveTarget["justify"] = "left" self.GiveTarget.place(x=110,y=120,width=327,height=30) # 删掉提前get值的代码,不需要全局变量y StartButton=tk.Button(root) StartButton["activebackground"] = "#90ee90" StartButton["activeforeground"] = "#ffffff" StartButton["bg"] = "#5fb878" ft = tkFont.Font(family='Times',size=10) StartButton["font"] = ft StartButton["fg"] = "#000000" StartButton["justify"] = "center" StartButton["text"] = "Start" StartButton.place(x=110,y=180,width=323,height=44) StartButton["command"] = self.StartButton_command def StartButton_command(self): #"Start" Button print("Start") # 修改:在点击按钮时,实时获取输入框的当前值 source_path = self.GiveSource.get() target_path = self.GiveTarget.get() print ("Source=" + source_path) print ("Target=" + target_path) print ("called HDD Copy") # 之后你就可以把这两个路径传给批处理脚本了,比如: # subprocess.Popen([r'HDD_Kopierer.bat', source_path, target_path]) if __name__ == "__main__": root = tk.Tk() app = App(root) root.mainloop()
关键修改说明
- 将Entry组件转为实例属性:用
self.xxx定义输入框,这样类的其他方法(比如按钮回调函数)就能访问到这些组件对象。 - 延迟获取输入值:不在初始化时调用
get(),而是在用户点击按钮时再获取,这样拿到的是用户输入后的最新内容。 - 移除不必要的全局变量:用实例属性管理组件比全局变量更符合面向对象的规范,也避免了全局变量带来的潜在问题。
这样修改后,点击Start按钮就能正确输出你输入的源路径和目标路径了,之后你只需要把这两个路径作为参数传给你的批处理脚本就行。
内容的提问来源于stack exchange,提问作者Techrpiest
相关产品推荐
相关产品推荐

