2017-09-20 6 views
-1

별도의 프로그램에서 tkinter 창에서 버튼을 클릭 할 때 python 프로그램 (예 : program.py)을 실행하고 싶습니다. 그러나 모듈에서 클래스를 가져 오면 실행됩니다. 클릭하면 모듈을 실행할 수있는 버튼을 어떻게 얻습니까? 어떤 도움이라도 대단히 감사합니다.Tkinter 버튼 - 가져 오기 및 실행 모듈

실행 (program.py)에

다른 모듈 : Tkinter를 버튼

class sampleProgram(): 
    def DoSomething(): 
     print('Do Something') 

모듈 :

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?**>) 
+0

표시된 코드로 (그리고'Class' 대신에'class' (모두 소문자)를 의미한다고 가정 할 때)'program' 모듈을 임포트 할 때 문제가 없습니다. 왜냐하면 import 될 때 클래스를 정의하기 때문입니다. – BlackJack

+0

@BlackJack - 답변 해 주셔서 감사합니다. 질문을 편집했지만 @ReblochonMasque의 원래 응답을 기반으로 작동하도록 만들 수있었습니다. 함수를 클래스에 두는 것이 아니라'staticmethod'를 사용하는 것에 대한 여러분의 의견을 설명해 주시겠습니까? 그것을 쓸 수있는 더 좋은 방법을 배울 수있는 기회에 감사드립니다! –

+0

메서드가 첫 번째 인수로 호출 된 인스턴스를 사용하지 않으면 실제로 메서드가 아니므로 [staticmethod()] (https://docs.python.org/2/)를 사용하여 메서드를 명확하게 만들어야합니다. library/functions.html # staticmethod). 그렇지 않으면 인스턴스에서 호출 할 수 없습니다. 또한 함수/"정적 메서드"를 클래스에 넣는 것은 코드 냄새입니다. 아주 드문 경우지만, 단지 클래스에 포함 된 함수 대신 단순히 일반 함수가 아닌 이유를 설명 할 수있는 경우에만 의미가 있습니다. – BlackJack

답변

0

클래스에서 DoSomething으로 전화해야합니다. 이 경우 가져 오기를 수행해야합니다. Tkinter를 버튼

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

모듈 :

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) 

당신은 runButton commandsampleProgram.DoDomething StaticMethod를 결합; 버튼을 클릭하면이 명령이 호출됩니다.

+0

'DoSomething'은 클래스 메소드가 아닙니다. 'classmethod'를 사용하여 클래스 메쏘드로 꾸며서 클래스 객체를 첫번째 인자로 가져와야합니다. 그래서 아마 여러분은 실제로'staticmethod'를 원할 것입니다. 그런 다음 함수가 왜 "클래스"로 옮겨 졌는지에 대한 질문을 던집니다. – BlackJack

+0

좋은 지적, 게시물을 수정했습니다. –

1

from program import DoSomething

그 버튼의 명령에 당신은 단순히 def DoSomething()

를 호출 할 수 있습니다

RunButton = Button(self, text="Run", command=DoSomething)