python-3.x - 如何使用 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'
解决方案
你可以试试:
with open("main.py", "r", encoding="utf-8") as file:
exec(file.read())
推荐阅读
- gcloud - gcloud 命令检查项目是否存在
- string - Python 3 查找所有重叠匹配
- python - 在散景服务器中选择线条颜色
- itext - iText PDF 表单:如何更改字段的工具提示?
- javascript - 为什么我的 for 循环包含一个 fetch API 调用只运行一次?
- jquery - 同一行中每个图像的高度相同的照片库
- tensorflow - 为什么 tf.estimator.DNNRegressor 预测负 y 值?
- python - 没有pk的django url
- php - Foreach 在 laravel 中使用不同查询从一个数据库表中调用值
- javascript - AmCharts Column fillColors IOS Safari & Chrome 上的全黑