Python 3.x 如何用一个按钮在Tkinter中执行Python 3程序
当我点击一个按钮时,我正试图从tkinter执行一个python 3文件 tkinter代码Python 3.x 如何用一个按钮在Tkinter中执行Python 3程序,python-3.x,tkinter,Python 3.x,Tkinter,当我点击一个按钮时,我正试图从tkinter执行一个python 3文件 tkinter代码 import tkinter as tk import subprocess as sub WINDOW_SIZE = "600x400" root = tk.Tk() root.geometry(WINDOW_SIZE) tk.Button(root, text="Create Motion!", command=lambda: sub.call('home/pi/motion1.py')).p
import tkinter as tk
import subprocess as sub
WINDOW_SIZE = "600x400"
root = tk.Tk()
root.geometry(WINDOW_SIZE)
tk.Button(root, text="Create Motion!", command=lambda: sub.call('home/pi/motion1.py')).pack()
但是当我运行程序时会出错
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.5/tkinter/__init__.py", line 1562, in __call__
return self.func(*args)
File "/home/pi/AnimationGUI.py", line 11, in <lambda>
tk.Button(root, text="Create Motion!", command=lambda: sub.call('motion1.py')).pack()
File "/usr/lib/python3.5/subprocess.py", line 247, in call
with Popen(*popenargs, **kwargs) as p:
File "/usr/lib/python3.5/subprocess.py", line 676, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.5/subprocess.py", line 1282, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'motion1.py'
Tkinter回调中出现异常
回溯(最近一次呼叫最后一次):
文件“/usr/lib/python3.5/tkinter/\uuuuu init\uuuuu.py”,第1562行,在调用中__
返回self.func(*args)
文件“/home/pi/AnimationGUI.py”,第11行,在
tk.Button(root,text=“Create Motion!”,command=lambda:sub.call('motion1.py')).pack()
文件“/usr/lib/python3.5/subprocess.py”,第247行,在调用中
将Popen(*popenargs,**kwargs)作为p:
文件“/usr/lib/python3.5/subprocess.py”,第676行,在__
恢复信号,启动新会话)
文件“/usr/lib/python3.5/subprocess.py”,第1282行,在执行子进程中
引发子项异常类型(errno\u num、err\u msg)
FileNotFoundError:[Errno 2]没有这样的文件或目录:“motion1.py”
你完全做错了。正确的方法是使“motion1.py”中包含一个函数来执行某些操作。假设您将该函数称为“main”(非常常见)。那么您的代码将是:
import tkinter as tk
import motion1
WINDOW_SIZE = "600x400"
root = tk.Tk()
root.geometry(WINDOW_SIZE)
btn = tk.Button(root, text="Create Motion!", command=motion1.main)
btn.pack()
假设您的代码和“motion1.py”在同一个文件夹中 调用按钮命令时,可以在函数中使用exec()
您应该避免使用lambda,而只使用常规函数
另外,为了确保文件被关闭,只需在exec()周围用块包装一个
您好,谢谢您的回复,我想这是我给出的绝对路径,我做错了什么?也许您需要在“home/pi/motion1.py”前面加一个“/”,谢谢它解决了这一部分,但现在获得[Errno 13]的权限被拒绝了?这个问题实际上是关于如何正确使用subprocess.call,而不是关于tkinter。所以不应该有tkinter代码或标签。有问题的最小程序是导入子进程;子流程调用('motion.py')
。请参阅上面的代码,但是,它不会绘制窗口来按下按钮,而是调用motion1.py并在btn=tk.button(root,text=“Create Motion!”,command=motion1.main)下面启动camera?错误消息AttributeError:模块“motion1”没有属性main@Coyney22你需要先把所有的代码放到一个名为“main”的函数中。谢谢你能给我一个上面有代码的函数的例子吗?我通过实践学习,谢谢你的帮助
from tkinter import *
window = Tk()
window.geometry("100x100")
window.title('Run another program')
def runsomething():
with open("yourpathhere.py") as file:
exec(open("thesamepathhere.py").read()) # exec() in python 3 is the equivalent of execfile() in python 2 #
btn = Button(window, text = "Run a program", command=runsomething)
btn.pack()
window.mainloop()