首页 > 解决方案 > 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()

谢谢

标签: pythonuser-interfacetkinter

解决方案


正如@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()

在此示例中,脚本和程序必须位于同一目录中。


推荐阅读