【问题标题】:command is performed without pressing button命令在不按下按钮的情况下执行
【发布时间】:2016-07-10 02:59:05
【问题描述】:

按下按钮执行的命令有问题(使用 Tkinter)。

我这样定义函数:

refPt = []
cropping = False

def main(image_dir):
    def click_and_crop(event, x, y, flags, param):
       global refPt, cropping


    if event == cv2.EVENT_LBUTTONDOWN:
        refPt = [(x, y)]
        cropping = True


    elif event == cv2.EVENT_LBUTTONUP:

        refPt.append((x, y))
        cropping = False


        cv2.rectangle(image, refPt[0], refPt[1], (0, 255, 0), 2)
        cv2.imshow("image", image)

image=cv2.imread(image_dir)
print (image.dtype)
clone = image.copy()
cv2.namedWindow("image")
cv2.setMouseCallback("image", click_and_crop) 

while True:

    cv2.imshow("image", image)
    key = cv2.waitKey(1) & 0xFF


    if key == ord("r"):
        image = clone.copy()


    elif key == ord("c"):
        break


if len(refPt) == 2:
    roi = clone[refPt[0][1]:refPt[1][1], refPt[0][0]:refPt[1][0]]
    cv2.imshow("ROI", roi)
    cv2.waitKey(0)
    cv2.imwrite('template.tif',roi)

cv2.destroyAllWindows()

当我单独测试时,它工作正常。

这是我的 GUI 代码的一小部分:

window = tkinter.Tk() window.title("Analog2Digital Transform") 
b2 =    tkinter.Button(window, text="Start", command=main('7_7026_polowa.tif'),   width=10, heigh=10)

现在,当我运行我的脚本函数 main() 时,会在显示 GUI 窗口之前执行。此外,它使用了函数的参数 - main('7_7026_polowa.tif'),它包含在 GUI 代码中。是函数定义还是 GUI 代码有问题?

【问题讨论】:

标签: python python-3.x opencv tkinter


【解决方案1】:

如果您想使用命令参数将函数绑定到小部件,则不能有括号。

command = main

因为使用它们它会调用函数。如果你想绑定函数并传入一个值,那么你应该看看lambda

command = lambda : main('7_7026_polowa.tif')

如果您使用 bind 方法而不是命令参数将函数绑定到小部件,那么您需要 lambda 来获取事件对象。

mywidget.bind("<ButtonRelease-1>", lambda e : function(e, value) )

或者,如果您不使用事件对象,则无需将其传递给函数。

mywidget.bind("<ButtonRelease-1>", lambda e : function(value) )

【讨论】:

    【解决方案2】:
    b2 =tkinter.Button(window, text="Start", command=main('7_7026_polowa.tif'),   width=10, heigh=10)
    

    main 在创建按钮时执行,因为括号“()”,并且 command=返回值。高度也拼错了。使用 partial 将值传递给函数,而 command=function --> 当你想调用函数而不传递值时不要使用括号。

    from functools import partial
    ...
    b2=tkinter.Button(window, text="Start", command=partial(main, '7_7026_polowa.tif'),
                      width=10, height=10)
    

    【讨论】:

      猜你喜欢
      • 2021-02-04
      • 2017-12-23
      • 1970-01-01
      • 1970-01-01
      • 2021-11-27
      • 1970-01-01
      • 2018-12-12
      • 1970-01-01
      • 2020-08-14
      相关资源
      最近更新 更多