看起来你正在通过
image_path
到
show_image
通过您的
func2
λ。当你设置
func2 = lambda: show_image(func1)
使命感
func1
内部show_image不会像您所期望的那样返回filepath字符串。相反,它调用
select(label)
返回
filepat
h、 但是你没有使用这个返回
filepath
正确地作为show_image的参数。你本质上是想展示
函数1
本身,而不是结果。
要解决此问题,您可以修改您的方法以确保
函数2
从select(label)接收作为字符串的文件路径,然后将其正确传递给show_image。你可以试试这样的方法:
import tkinter as tk
import tkinter.filedialog as fd
import cv2
def select(label):
filepath = fd.askopenfilename()
text = "Selected image: {}".format(filepath)
label.config(text=text)
return filepath
def show_image(image_path):
image = cv2.imread(image_path)
cv2.imshow("Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
root = tk.Tk()
root.geometry("600x400")
frame = tk.Frame(root)
frame.pack()
label_frame = tk.LabelFrame(frame)
label_frame.grid()
label = tk.Label(frame, text="Label")
label.grid()
# Use a global variable to store the selected filepath
selected_filepath = None
def update_filepath():
global selected_filepath
selected_filepath = select(label)
def display_image():
global selected_filepath
if selected_filepath:
show_image(selected_filepath)
button1 = tk.Button(frame, text="select", command=update_filepath)
button1.grid()
button2 = tk.Button(frame, text="show", command=display_image)
button2.grid()
root.mainloop()