Question

Is there a better way to implement a code like this without using global parameters? I was taught that global parameters generally isnt a good thing in python. What do you guys think? do you think global parameters are okay?

This is the code

import Tkinter as tk


def main():    
    global root

    root = tk.Tk()   # parent window


    message = tk.Label(root, text = "Hello World") 
    message.pack() 

    buttton = tk.Button(root, text="exit", command = buttonPushed) 
    button.pack()

    tk.mainloop()  


def buttonPushed():
    global root
    root.destroy()

main()

on the line where I create the button, if instead I write something like this;

buttton = tk.Button(root, text="exit", command = buttonPushed(root)) 
button.pack()


def buttonPushed(root):
    root.destroy()    

the program will not work as required.

Any suggestions?

Was it helpful?

Solution

Your buttonPushed function is unnecessary because you can assign the button's command parameter to the root.destroy function directly:

button = tk.Button(root, text="exit", command=root.destroy) 

Thus, your code becomes just this1:

import Tkinter as tk

def main():    

    root = tk.Tk()

    message = tk.Label(root, text="Hello World") 
    message.pack() 

    button = tk.Button(root, text="exit", command=root.destroy) 
    button.pack()

    tk.mainloop()  

main()

1Note: I also removed the global root line at the top of main because it is unnecessary.

OTHER TIPS

You can write it using classes but as iCodez says, that button is kind of unnecessary right now.

import Tkinter as tk

class interface(tk.Frame):
    def __init__(self, root):
        tk.Frame.__init__(self, root)

        self.root = root
        message = tk.Label(self.root, text = "Hello World") 
        button = tk.Button(self.root, text="exit", command = self.buttonPushed) 

        message.pack()
        button.pack()

    def buttonPushed(self):
        self.root.destroy()

root = tk.Tk()
inter = interface(root)
root.mainloop()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top