解决class App(Pred_Temp):
def __init__(self):
super().__init__()
def show_res(self, entry, text):
input_str = entry.get()
# 在 Text 控件中显示字符串
text.delete('1.0', tk.END)
text.insert(
tk.END,
Pred_Temp().main(input_str)
)
return input_str
def to_clipboard(self, text):
text_str = text.get("1.0", tk.END)
# 复制内容到剪切板
root.clipboard_clear()
root.clipboard_append(text_str)
return text_str
def show_trace(self):
return
def to_excel(self):
return
def run(self):
root = tk.Tk()
root.title("重庆退火出炉物料冷却时间预测")
root.geometry("550x300")
entry = tk.Entry(root, width=70)
entry.pack()
button = tk.Button(root, text="预测冷却完成时间(50摄氏度)", command=self.show_res(entry, text))
button.pack()
copy_button = tk.Button(root, text="复制到剪切板", command=self.to_clipboard(text))
copy_button.pack()
text = tk.Text(root)
text.pack()
root.mainloop()
if __name__ == "__main__":
App().run()
UnboundLocalError Traceback (most recent call last)
Cell In[16], line 50
47 root.mainloop()
49 if __name__ == "__main__":
---> 50 App().run()
Cell In[16], line 38, in App.run(self)
35 entry = tk.Entry(root, width=70)
36 entry.pack()
---> 38 button = tk.Button(root, text="预测冷却完成时间(50摄氏度)", command=self.show_res(entry, text))
39 button.pack()
41 copy_button = tk.Button(root, text="复制到剪切板", command=self.to_clipboard(text))
UnboundLocalError: cannot access local variable 'text' where it is not associated with a value
这个错误是因为在创建 button
和 copy_button
时,你试图使用 text
变量,但是在那个时候 text
还没有被定义。你应该先创建 text
,然后再创建 button
和 copy_button
。以下是修改后的代码:
class App(Pred_Temp):
def __init__(self):
super().__init__()
def show_res(self, entry, text):
input_str = entry.get()
# 在 Text 控件中显示字符串
text.delete('1.0', tk.END)
text.insert(
tk.END,
Pred_Temp().main(input_str)
)
return input_str
def to_clipboard(self, text):
text_str = text.get("1.0", tk.END)
# 复制内容到剪切板
root.clipboard_clear()
root.clipboard_append(text_str)
return text_str
def show_trace(self):
return
def to_excel(self):
return
def run(self):
root = tk.Tk()
root.title("重庆退火出炉物料冷却时间预测")
root.geometry("550x300")
entry = tk.Entry(root, width=70)
entry.pack()
text = tk.Text(root)
text.pack()
button = tk.Button(root, text="预测冷却完成时间(50摄氏度)", command=lambda: self.show_res(entry, text))
button.pack()
copy_button = tk.Button(root, text="复制到剪切板", command=lambda: self.to_clipboard(text))
copy_button.pack()
root.mainloop()
if __name__ == "__main__":
App().run()
注意,我还在 command
参数中添加了 lambda:
,这是因为你需要在按钮被点击时才调用函数,而不是在按钮被创建时就调用函数。如果不使用 lambda:
,那么函数会在按钮被创建时就被调用,这可能不是你想要的结果。希望这个解答能帮到你!