Class in tkinter

type or paste code here
``from tkinter import *
from tkinter import messagebox
from tkinter import ttk

class App(Frame):
    def __init__(self,screen=None):
        super().__init__(screen)
        self.master=screen
        self.createwidget()
    def createwidget(self):
        self.btn1=Button(self.master,text="test but",command=OnclickButton).pack()

    #event
    def OnclickButton(self):
        print("hi")


if __name__="__main__" :
    screen=Tk()
    pageme=App(screen)
    screen.mainloop()
    pass

can anyone help me with this code? what is wrong with the part name=“main”?

Couple of things,

  1. You should not do wildcard imports eg (from tkinter import *). This can cause problems in many ways.

  2. You subclass Frame but, don’t use it.

  3. When creating widgets best practice is to not attach the pack or grid to creation eg
    btn = tk.Button().pack()
    instead do
    btn = tk.Button()
    btn.pack()

  4. In your command call command=OnClickButton, should be self.OnClickButton

  5. Why are you using pass in the object creation?

Here is a quick example for you to work with

import tkinter as tk
from tkinter import messagebox

class App:
    def __init__(self, parent):
        parent.geometry('400x200+350+350')
        self.parent = parent
        self.createwidget()

    def createwidget(self):
        btn = tk.Button(self.parent, text='Button', command=self.clickbutton)
        btn.pack()

    def clickbutton(self):
        messagebox.showinfo('Info', 'You clicked the button')


if __name__ == '__main__':
    screen = tk.Tk()
    pagename = App(screen)
    screen.mainloop()

this should be a comparison not an assignment

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.