简体   繁体   中英

Python Application not running in visual studio

I'm starting my journey learning Python and am working through a NOOB's book.

I've just started on the GUI section and am having problems getting the app to run in the root window.

My code is

from tkinter import *

class Application(Frame):
    """GUI application which counts button clicks."""
    def _init_(self, master):
        super(Application, self)
        self.grid()
        self.bttn_clicks = 0
        self.create_widget()

    def create_widget(self):
        """ Create buttong that displays the number of clicks. """
        self.bttn = Button(self)
        self.bttn["text"]= "Total Clicks: 0"
        self.bttn["command"] = self.update_count
        self.bttn.grid()

    def update_count(self):
        """ Increase click count and display new total. """
        self.bttn_clicks += 1
        self.bttn["text"] = "Total Clicks: " + str(self.bttn_clicks)

#main
root = Tk()
root.title("Click Counter")
root.geometry("300x115")

app = Application(root)

root.mainloop()

The root window open but no button appears?

Am i doing something wrong? or is it due something like the fact I'm using Visual Studio?

Any help is greatly received.

Thanks

You have not named your __init__ method correctly. It needs two underscores on each side of init . If you don't get the name exactly right, Python ignores it (as it's just a normal method with a strange name) and uses the default __init__ (which doesn't do what you need).

There's one further issue with your __init__ method. Your call to super(Application, self) also probably doesn't work right, as you're not doing anything with the return value from super . You probably want that to be:

super(Application, self).__init__(master)

I discovered there was a typo in my code.

i was missing ' .__init__(master) ' from the class, which meant i wasn't initializing the frame.

code below now works.

    from tkinter import *

class Application(Frame):
    """GUI application which counts button clicks."""
    def __init__(self, master):
        super(Application, self).__init__(master)
        self.grid()
        self.bttn_clicks = 0
        self.create_widget()

    def create_widget(self):
        """ Create buttong that displays the number of clicks. """
        self.bttn = Button(self)
        self.bttn["text"]= "Total Clicks: 0"
        self.bttn["command"] = self.update_count
        self.bttn.grid()

    def update_count(self):
        """ Increase click count and display new total. """
        self.bttn_clicks += 1
        self.bttn["text"] = "Total Clicks: " + str(self.bttn_clicks)

#main
root = Tk()
root.title("Click Counter")
root.geometry("300x115")

app = Application(root)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM