Home > Blockchain >  How to self invoke the tkinter button?
How to self invoke the tkinter button?

Time:02-18

I m new to GUI and Tkinter.

I m trying to invoke a function or script without pressing a button from the GUI. It should run the function as soon as the GUI opens.

def example_fun():
    print("this does something...")

img0 = PhotoImage(file = f"img0.png")
b0 = Button(
    image = img0,
    borderwidth = 0,
    highlightthickness = 0,
    command = example_fun,
    relief = "flat")

What is the best way to run the script as soon as GUI opens?

CodePudding user response:

You can run (also referred to as call) the function once when the code first runs by simply calling the function in the main body. Something like

example_fun()
b0 = Button(
    master = root,
    image = img0,
    borderwidth = 0,
    highlightthickness = 0,
    command = example_fun,
    relief = "flat")

will call your function once, while also assigning the same function to your button. Note you were missing the parent argument in your Button, I added it in for you.

CodePudding user response:

The main Python term usually describes the part of code where there is no identation because that is the main scope. In this code example_fun() at the end of your code with no identation to get that running. But this code won't pass the interpreter because main() in that function is calling a function main that is not defined here.

  • Related