INear
INear

Reputation: 29

Making a basic user interface with tkinter-python

I've just been trying to practice some code by making a simple dice game

and using tkinter for the user interface of the starting menu for the game

For the starting menu, I'm trying to just see how it will come out if I used the code below,

BUT before making the Button widget and the Label Widgets, the commands come up first.

How would I fix this up?

thanks in advance


import tkinter as tk
from main import main
from written import showInstructions, showCredits
from generate_no import generate_no

class DiceGameUI(tk.Frame):
    def __init__(self, master = None):
        tk.Frame.__init__(self, master)
        self.grid()
        self.createWidgets()

    def createWidgets(self):
        self.titleLabel = tk.Label(self, fg = "red")    #The Title of the Game
        self.titleLabel["text"] = "Dice Game"

        self.startButton = tk.Button(self)              #Start Button
        self.startButton["text"] = "Roll On!"
        self.startButton["command"] = main()            <<----- This plays out first before 
        self.startButton.grid()                                 making any widgets

        self.instrButton = tk.Button(self)              #Instructions Button
        self.instrButton["text"] = "Instructions"
        self.instrButton["command"] = showInstructions()
        self.instrButton.grid()

        self.credits = tk.Button(self)                  #Credits Button
        self.credits["text"] = "Credits"
        self.credits["command"] = showCredits()
        self.credits.grid()


root = tk.Tk()                                          #Run code using tkinter
app = DiceGameUI(master = root)
app.mainloop()

'

Upvotes: 0

Views: 855

Answers (1)

furas
furas

Reputation: 143187

You have to assign only name of function without () and arguments

self.startButton["command"] = main

If you use () than you run that function and result is assigned to command. It is good to create dynamicly function for command.

If you will need assign function which require arguments you have to use lambda function.

self.startButton["command"] = lambda:main()

self.startButton["command"] = lambda:main("abc", 123)

a = "abc"
b = 123
self.startButton["command"] = lambda arg1=a,arg2=b:main(arg1,arg2)
self.startButton["command"] = lambda title=a,count=b:main(title,count)

# this may not work - especially if a or b changes value (for example in loop)
self.startButton["command"] = lambda:main(a, b)

example how to use function name in own code

def plus(a, b):
   return a + b

def minus(a, b):
    return a - b

def result(a, b, func_name):
    return func_name(a,b)

print result(10, 7, plus) # 17
print result(10, 7, minus) # 3

Upvotes: 1

Related Questions