Tkinter将按钮链接到不同的脚本

2024-10-02 08:18:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在正在探索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()

谢谢


Tags: 代码inpyimportmastertkinterdefgui
1条回答
网友
1楼 · 发布于 2024-10-02 08:18:04

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

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

相关问题 更多 >

    热门问题