简体   繁体   中英

Tkinter - Linking buttons to different scripts

I am exploring GUI's at the moment. What I want is to have a GUI with a 2 buttons and I want each of the buttons to run a separate python script when clicked. I have outlined my code below (the first button runs just fine but I am having issues with the second button.

Error Message when I choose the second button:

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)

Code:

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()

Thanks

As @matiiss suggested importing the other scripts into your program can help and it can be done like this,

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()

here for this example the scripts and the program must be in same directory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM