python - Tkinter - 将按钮链接到不同的脚本
问题描述
我目前正在探索 GUI。我想要的是有一个带有 2 个按钮的 GUI,并且我希望每个按钮在单击时运行一个单独的 python 脚本。我在下面概述了我的代码(第一个按钮运行得很好,但我遇到了第二个按钮的问题。
选择第二个按钮时出现错误消息:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
代码:
from tkinter import *
import tkinter as tk
master = Tk()
def First_Scriptcallback():
exec(open(r'Desktop\Automation\First_Script.py').read())
def second_Scriptcallback():
exec(open(r'Desktop\Automation\Second_Script.py').read())
#master.title("Test GUI")
#canvas = tk.Canvas(master, height=300, width = 400)
#canvas.pack()
firstButton = Button(master, text="Run first script", command=First_Scriptcallback)
firstButton.pack()
secondButton = Button(master, text="Run second script", command=second_Scriptcallback)
secondButton.pack()
mainloop()
谢谢
解决方案
正如@matiiss 建议的那样,将其他脚本导入您的程序会有所帮助,并且可以这样做,
import First_Script as first
import Second_Script as second
from tkinter import *
import tkinter as tk
master = Tk()
def First_Scriptcallback():
first.function_name()#here you must create functions in first_script to call in this main script
def second_Scriptcallback():
second.function_name()
#master.title("Test GUI")
#canvas = tk.Canvas(master, height=300, width = 400)
#canvas.pack()
firstButton = Button(master, text="Run first script", command=First_Scriptcallback)
#command=first.function_name
#we can also directly call an function using above command,but sometimes there are problems related to this approch
firstButton.pack()
secondButton = Button(master, text="Run second script", command=second_Scriptcallback)
#command=second.function_name
secondButton.pack()
mainloop()
在此示例中,脚本和程序必须位于同一目录中。
推荐阅读
- mysql - JSON_EXTRACT 和方括号
- r - 更改 R 中数据框列中的所有值
- symfony - Symfony 4 第一个事件
- valgrind - VSTS 托管 Linux - valgrind 失败 - 没有新的代码更改
- cryptography - Nim 中的 Cryptopals 1.2:XOR 返回意外值
- python - Python CSV 解析字典和查找元素的索引
- c# - 从 IIS 中的网站重新启动和监视服务
- php - 通过表单提交更改 PHP 变量/值
- c# - 如何使用 AVCaptureVideoDataOutput 在 AVCaptureSession 中避免丢帧
- bond - C# 绑定:字符串到 wstring