-1

I try to make a GUI using Tkinter. However, it is not working. It runs my function first. Where did I do it wrong?

    import pyttsx3
    from openpyxl import load_workbook
    from tkinter import *
    
    def Do_test():
        i=0
        wb = load_workbook('words.xlsx')
        ws = wb.active
        for row in ws.values:
            for value in row:
                engine = pyttsx3.init()
                engine.say(value)
                engine.runAndWait()
                Ans = input("please enter the word")
                if Ans == value:
                    print ("Right")
                else:
                    print("wrong")
                    i = i+1
                    wrong = value
                    ws.cell(row=i, column=2, value=wrong)
        wb.save('result.xlsx')
    
    root = Tk()
    
    myButton = Button(root, text="Run", command=Do_test())
    myButton.pack()
    
    root.mainloop()

Thanks so much for the help

Azeame
  • 2,322
  • 2
  • 14
  • 30

3 Answers3

2
myButton = Button(root, text="Run", command=Do_test())

dont use () in the command call

Right:

myButton = Button(root, text="Run", command=Do_test)
Legit007
  • 181
  • 1
  • 8
1

You only have a small right in the last third line

myButton = Button(root, text="Run", command=Do_test())

here you wrote command=Do_test() ... This is wrong ... the parentheses () call a method, it is called as soon as the GUI will start... you have to remove the parenthese in orderr to make a function run on clicking the button..... like this command=Do_test

just replace that line by the following with proper indentation and your issue will be solved

myButton = Button(root, text="Run", command=Do_test)
Prakhar Parikh
  • 177
  • 2
  • 13
0

When you want to associate a function to a Tkinter button, you don't have to insert brackets. Otherwise when the script starts it runs as if you normally call it. To assign the function to the button, simply give it the name of the function without the brackets. So just write:

myButton = Button(root, text="Run", command=Do_test)

For passing parameter:

Do_test = the_test(param1, param2)
myButton = Button(root, text="Run", command=Do_test)
Piero
  • 404
  • 3
  • 7
  • 22