2014-11-19 4 views
0

가져온 모듈 내에서 위젯을 추가하거나 삭제하는 방법을 알고 싶습니다. 나는 그들에게 정확하게 접근하지 못한다. OOP를 사용하면 쉽게 할 수 있지만 OOP를 이해하려고 노력하고 원리는 쉽지만 세부 사항에 대해서는 머리를 맞지 않습니다. 따라서 적절한 교사가 부족하기 때문에 절차 적 솔루션이 필요합니다.다른 모듈 내에서 tkinter 위젯 추가 또는 삭제

이 주 스크립트입니다

#!/usr/bin/python 

try: 
    # Python2 
    import Tkinter as tk 
except ImportError: 
    # Python3 
    import tkinter as tk 

import os 
import sys 

sys.path.append(os.path.dirname(os.path.realpath(__file__))) 

import target 

def myfunction(event): 
    canvas.configure(scrollregion=canvas.bbox("all"),width=300,height=200) 

def test(): 
    target.secondWindow() 

root = tk.Tk() 
root.geometry("600x350+30+50") 

myframe = tk.Frame(root,relief="groove",bd=1) 
myframe.place(x=20, y=30, width=560, height=200) 

canvas = tk.Canvas(myframe) 
frame = tk.Frame(canvas) 
myscrollbar=tk.Scrollbar(myframe, orient="vertical", command=canvas.yview) 
canvas.configure(yscrollcommand=myscrollbar.set) 

myscrollbar.pack(side="right", fill="y") 
canvas.pack(side="left") 
canvas.create_window((0,0), window=frame, anchor='nw') 

allMissions = { 
    "1":{"name":"go"}, 
    "2":{"name":"see"}, 
    "3":{"name":"win"}, 
    "4":{"name":"party"}} # this would be a text file 

for a in allMissions.keys(): 
    mn = allMissions[a]["name"] 
    tk.Label(frame, text=mn, justify="left").grid(row=int(a), column=0) 

# what's bind really doing? 
frame.bind("<Configure>", myfunction)  

test = tk.Button(root, command=test, text="TEST") 
test.place(x = 20, y = 250, width=580, height=40) 

tk.mainloop() 

이 가져온 모듈 : 두 번째에 어떤 위젯의 메모리 주소를 전달하여 당신이 그것을 할 target.py

try: 
    # Python2 
    import Tkinter as tk 
except ImportError: 
    # Python3 
    import tkinter as tk 

def changeMainWindow(): 
    # here's where I'm stuck 
    print("What do I have to do to add a new") 
    print("label in the main window from here?") 
    print("Or to delete it?") 


def secondWindow(): 


    amWin = tk.Toplevel() 

    amWin.geometry("300x200+720+50") 

    button = tk.Button(amWin, text="OK", command=changeMainWindow) 
    button.place(x = 20, y = 80, width=260, height=30) 

    #amWin.mainloop() comment noticed (: 
+0

두 번째 모듈에 문제가 있습니다. 'mainloop'을 호출해서는 안됩니다. –

+0

감사합니다, 당신 말이 맞아요. 나는 그것을 바로 잡았다. –

답변

0

프로그램. 기존 인스턴스에 포인터를 전달할 수 있기 때문에 Tkinter를 다시 가져올 이유가 없습니다. Tkinter로 간단한 실험을하는 것 이상의 일을한다면, 먼저이 온라인 사이트 중 하나에서 수업을 배울 가치가 있습니다. http://www.greenteapress.com/thinkpython/html/thinkpython016.html More here https://wiki.python.org/moin/BeginnersGuide/NonProgrammers
많은 답을 얻지 못할 것입니다 대부분의 프로그래머가 AFAIK 클래스 구조를 사용하기 때문에 프로그램이 구조화 된 방식이므로 코드를 비 클래스 환경에 주입하는 방법을 모르므로 응답이 없습니다. 아래의 첫 번째 프로그램이 클래스를 사용하면 두 번째 프로그램의 클래스를 상속 할 수 있고 함수는 첫 번째 프로그램 클래스의 일부가되며 기존 클래스와 동일한 방식으로 액세스 할 수 있으므로 포인터가 전달되거나 다른 해킹이 발생하지 않습니다 , 필요할 것입니다.

## I deleted some code for simplicity 
def myfunction(event): 
    canvas.configure(scrollregion=canvas.bbox("all"),width=300,height=200) 

def test(): 
    TG.secondWindow() 

root = tk.Tk() 
root.geometry("600x350+30+50") 

myframe = tk.Frame(root,relief="groove",bd=1) 
myframe.place(x=20, y=30, width=560, height=200) 

canvas = tk.Canvas(myframe) 
frame = tk.Frame(canvas) 
myscrollbar=tk.Scrollbar(myframe, orient="vertical", command=canvas.yview) 
canvas.configure(yscrollcommand=myscrollbar.set) 

myscrollbar.pack(side="right", fill="y") 
canvas.pack(side="left") 
canvas.create_window((0,0), window=frame, anchor='nw') 

# what's bind really doing? 
frame.bind("<Configure>", myfunction)  

test = tk.Button(root, command=test, text="TEST", bg="lightblue") 
test.place(x = 20, y = 250, width=580, height=40) 

tk.Button(root, text="Quit All", command=root.quit, 
     bg="orange").place(x=20, y=300) 

""" instance of the class in the imported program 
    a pointer to the root window and the Tk instance are passed 
""" 
TG=target.Target(tk, root) 

tk.mainloop() 

target.py. 가져 오기가 없습니다.

class Target(): 
    def __init__(self, tk, root): 
     self.tk=tk 
     self.root=root 

    def changeMainWindow(self): 
     # here's where I'm stuck 
     self.tk.Label(self.amWin, bg="yellow", text =""""What do I have to do to add a new 
label in the main window from here? 
Or to delete it?""").place(x=50,y=20) 

    def secondWindow(self): 

     self.amWin = self.tk.Toplevel(self.root) 
     self.amWin.geometry("300x200+720+50") 

     button = self.tk.Button(self.amWin, text="Add Label", 
           command=self.changeMainWindow) 
     button.place(x = 20, y = 90, width=260, height=30). 
+0

지금까지 고맙습니다. 작동하도록 코드가 있지만 변경된 위젯은 하위 창에 있습니다. 메인 윈도우, 특히 표시된리스트에 위젯을 어떻게 추가합니까? –

+0

나는 당신의 대답을 아주 많이 승인하고 싶습니다. 따라서 target.py에서 메인 윈도우의 위젯을 변경할 수 있다면 그렇게 할 것입니다. –

+0

흠, 그래서 속임수는 처음에는 init 메소드 이외의 것을 사용하지 않고 많은 수의 객체를 만드는 것이고, 내부의 모든 메소드는 참조를 가지고 있습니까? 와우, 얼음이 좀 부서 질 수도있어. 시원한 –