Python Tkinter按钮-导入和运行模块

Python Tkinter按钮-导入和运行模块,python,tkinter,tk,Python,Tkinter,Tk,我希望在单独的程序中单击tkinter窗口中的按钮时运行python程序(ex:program.py)。但是,当我从模块导入类时,它会运行。单击按钮时,如何让按钮运行模块?非常感谢您的帮助 要运行的其他模块(program.py): 带tkinter按钮的模块: from program import DoSomething class Window(Frame) def __init__(self,master = None): <Stuff In Window

我希望在单独的程序中单击tkinter窗口中的按钮时运行python程序(ex:program.py)。但是,当我从模块导入类时,它会运行。单击按钮时,如何让按钮运行模块?非常感谢您的帮助

要运行的其他模块(program.py):

带tkinter按钮的模块:

from program import DoSomething

class Window(Frame)
    def __init__(self,master = None):
        <Stuff In Window>

    def addWidgets(self):
        <Widgets To Add>

    def init_window(self):
        self.pack(fill=BOTH, expand=1)
        RunButton = Button(self, text="Run", command=<**What Goes Here To Run sampleProgram?**>)
从程序导入DoSomething
类窗口(框架)
def uuu init uuu(self,master=None):
def addWidgets(self):
def初始窗口(自):
self.pack(填充=两者,扩展=1)
RunButton=按钮(self,text=“Run”,command=)

来自程序导入DoSomething

在该按钮的命令上,您只需调用
def DoSomething()


RunButton=Button(self,text=“Run”,command=DoSomething)
从程序导入DoSomething

在该按钮的命令上,您只需调用
def DoSomething()


RunButton=Button(self,text=“Run”,command=DoSomething)
您必须在
sampleProgram
类上调用
DoSomething
;为此,必须导入它

Class sampleProgram():
    def DoSomething():              # <--- this is a staticmethod
        print('Do Something')
Class sampleProgram():

def DoSomething():#您必须在
sampleProgram
类上调用
DoSomething
;为此,必须导入它

Class sampleProgram():
    def DoSomething():              # <--- this is a staticmethod
        print('Do Something')
Class sampleProgram():

def DoSomething():#
DoSomething
不是类方法。您需要使用
classmethod
将其修饰为一个类,并且它必须将类对象作为第一个参数。所以,也许你真的想要一个
静态方法
。这就引出了一个问题,为什么函数被移动到“类”中。
DoSomething
不是类方法。您需要使用
classmethod
将其修饰为一个类,并且它必须将类对象作为第一个参数。所以,也许你真的想要一个
静态方法
。这就引出了一个问题:为什么函数被移动到一个“类”中。通过显示的代码(假设您指的是
class
(全小写)而不是
class
),导入
程序
模块没有问题,因为导入时它只定义了一个类。@BlackJack-谢谢您的回答。我已经编辑了这个问题,但根据@ReblochonMasque的原始回复,我能够使它生效。你能解释一下你对使用
staticmethod
而不是将函数放在类中的评论吗?我很感激有机会学习更好的写作方法!如果一个方法没有把它被调用的实例作为第一个参数,那么它就不是一个真正的方法,这一点应该用下面的例子来说明。否则就不能在实例上调用它。在类中放置函数/静态方法也是一种代码味道。在极少数情况下,这是有意义的,但前提是你能解释为什么它不是一个简单的普通函数,而不是一个填充到类中的函数导入
程序
模块没有问题,因为导入时它只定义了一个类。@BlackJack-感谢您的回复。我已经编辑了这个问题,但根据@ReblochonMasque的原始回复,我能够使它生效。你能解释一下你对使用
staticmethod
而不是将函数放在类中的评论吗?我很感激有机会学习更好的写作方法!如果一个方法没有把它被调用的实例作为第一个参数,那么它就不是一个真正的方法,这一点应该用下面的例子来说明。否则就不能在实例上调用它。在类中放置函数/静态方法也是一种代码味道。在极少数情况下,这是有意义的,但前提是您能够解释为什么它不仅仅是一个普通函数,而不是一个填充到类中的函数。
from program import sampleProgram   # <--- import the class sampleProgram

Class Window(Frame)
    def __init__(self,master = None):
        <Stuff In Window>

    def addWidgets(self):
        <Widgets To Add>

    def init_window(self):
        self.pack(fill=BOTH, expand=1)
        RunButton = Button(self, text="Run", command=sampleProgram.DoDomething)