Home > Back-end >  Tkinter lambda command is inable to call a whole script
Tkinter lambda command is inable to call a whole script

Time:07-23

I had a script that looked like this:

add_game_btn = Button(top_menu,text="ADD GAME",command=add_game.create_game)

which seemed to work perfectly for me, executing the command when the button was pressed.

I soon moved the command to the whole another py file, so now the code looks like this:

import create_game
add_game_btn = Button(top_menu,text="ADD GAME",command=create_game)

create_game is another python script that I have in the same directory

The problem is when I run the script it automatically executes that script, even putting in lambda doesn't work. Does anyone know how I could make this work?

CodePudding user response:

You can't run an entire python file in that way, but you can create a function in the file that needs to be imported and then run that function like so:

Content of create_game.py (the file that needs to be executed on button click)

def my_game_function():
    print("Game created!")
    # Do your things here

Content of main.py

import tkinter as tk
import create_game

top_menu = tk.Tk()
add_game_btn = tk.Button(top_menu, text="ADD GAME", command=create_game.my_game_function)

add_game_btn.place(
    relx=0.5,
    rely=0.5,
    anchor="center"
)

top_menu.mainloop()

The function my_game_function will be executed on button click.

  • Related