OOP模式下Tkinter如何向函数传递输入框值?
问题解决方法
问题出在graphInA和graphInB是initUI方法里的局部变量,类的其他方法无法直接访问。解决核心是把这两个控件定义为类的实例属性,让整个类的方法都能调用。
具体修改步骤:
- 在
initUI方法中,给输入框变量加上self.前缀,将其绑定为实例属性:self.graphInA = CTtk.CTkEntry(width=50) self.graphInA.grid(row=0, column=2) self.graphInB = CTtk.CTkEntry(width=50) self.graphInB.grid(row=0, column=4) - 在
calBut方法中,通过self.前缀访问这两个输入框; - 注意:将字符串转换为浮点数失败时抛出的是
ValueError,不是TypeError,需要修正异常捕获类型。
修改后的完整代码:
import customtkinter as CTtk from tkinter import messagebox class App(CTtk.CTk): def __init__(self): super().__init__() self.initUI() # self.checkNaN() # 原代码中未实现该方法,暂时注释避免报错 def initUI(self): self.title("График функции") CTtk.set_appearance_mode("dark") CTtk.CTkLabel(text="Введите пределы интегрирования").grid(row=0,column=0) CTtk.CTkLabel(text="до", width=50).grid(row=0,column=1) CTtk.CTkLabel(text="и от", width=50).grid(row=0,column=3) self.graphInA = CTtk.CTkEntry(width=50) self.graphInA.grid(row=0, column=2) self.graphInB = CTtk.CTkEntry(width=50) self.graphInB.grid(row=0, column=4) but = CTtk.CTkButton(text="Рассчитать", fg_color="black", width=50, command=self.calBut) but.grid(row=0, column=5, padx=10) def calBut(self): a_input = self.graphInA.get().strip() b_input = self.graphInB.get().strip() if not a_input or not b_input: messagebox.showinfo("Ошибка", "Введите значение") return try: a = float(a_input) b = float(b_input) except ValueError: messagebox.showinfo("Ошибка", "Значение не число") return # 这里可以添加后续计算逻辑,比如使用a和b进行积分计算 print(f"Пределы интегрирования: от {a} до {b}") app = App() app.mainloop()
额外说明:
- 原代码中的
checkNaN()方法未实现,暂时注释避免运行报错; - 增加了
.strip()处理输入,避免用户输入空格导致的空值误判; - 优化了逻辑结构,提前返回减少嵌套,代码更清晰。
内容的提问来源于stack exchange,提问作者bigidulka
相关产品推荐
相关产品推荐

