Search code examples
pythontkinterpython-moduletkinter-button

Getting button input from module on tkinter python


I am working on a project that uses buttons, but I would like to make it modular. The only problem I can't seem to get pass by is getting if someone is pressing the button from a different file

-file 1

from tkinter import*
class app2:
    def __init__(self):
        s = Tk()

        but = Button(text="Test",command=subcommand)
        but.pack()
        s.mainloop()


def subcommand():
    x = command()
    x.command



class command:
    def __init__(self,int):
        self.command = ()










y = app2()

file 2-

from tkinter import*
from idea2 import *


def clicked():
    print("HI")



x = command()
x.command(clicked())

My code basically just takes a function from another file and loads it into the command class. So basically the button can get different commands from different files. I don't know what to put for "x = command(???)" because I am trying to get that from a different file.

Basic question: How to make my Tkinter button modular.

SOLVED


Solution

  • just pass the callback into the app2 constructor

    file1

    from tkinter import*
    class app2:
        def __init__(self,btn_callback=subcommand):
            s = Tk()
    
            but = Button(text="Test",command=btn_callback)
            but.pack()
            s.mainloop()
    

    file2

    from idea import app2
    def my_callback(*args,**kwargs):
        print("Buttton pressed...")
    app = app2(my_callback)
    

    or better yet make use of the event system in tkinter ... something like this

    import tkinter as Tkinter
    import tkinter.messagebox as tkMessageBox
    
    
    def helloCallBack(*a,**kw):
       tkMessageBox.showinfo( "Hello Python", "Hello World")
    
    class MyApp(Tkinter.Tk):
        def __init__(self):
            super().__init__()
            self.b = Tkinter.Button(self, text ="Hello", command = lambda:self.event_generate("<<button_click>>"))
            self.b.pack()
    
    app = MyApp()
    app.bind("<<button_click>>",helloCallBack)
    app.mainloop()