首页 > 解决方案 > 如何使用 tkinter 按钮执行 python 文件?

问题描述

我已经创建了 python 文件,一个是我的主程序文件,另一个是我的 tkinter 程序文件我要做的是使用 kinter.py 执行 main.py 文件但是当我运行 kinter 文件时它会出错。

主要.py:

import cv2
import numpy as np
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

videocapture = cv2.VideoCapture(0)
scale_factor = 1.3

while 1:
    ret ,pic=videocapture.read()

    faces = face_cascade.detectMultiScale(pic,scale_factor,5)
    for(x, y, w, h) in faces:
        cv2.rectangle(pic, (x, y), (x + w, y+h), (255, 0, 0), 2)
        font = cv2.FONT_HERSHEY_SIMPLEX
        cv2.putText(pic, 'Person', (x, y), font, 2, (0,0,255), 2, cv2.LINE_AA)

    print("Number of faces found {}".format(len(faces)))
    cv2.imshow('face', pic)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break
cv2.destroyAllWindows()

kinter.py:

import tkinter as tk
root = tk.Tk()
def callback():
    exec("main.py")
b =tk.Button(root,text="Run the Face Detection",command=callback)
b.pack()

root.mainloop()

错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\sanjay\AppData\Local\Programs\Python\Python39-32\lib\tkinter\__init__.py", line 1885, in __call__
    return self.func(*args)
  File "C:/Users/sanjay/PycharmProjects/pythonmini/kinter.py", line 4, in callback
    exec("main.py")
  File "<string>", line 1, in <module>
NameError: name 'main' is not defined'

标签: python-3.xopencvtkinter

解决方案


你可以试试:

with open("main.py", "r", encoding="utf-8") as file:
       exec(file.read())

推荐阅读