K-Doe
K-Doe

Reputation: 559

Preventing circular import example

Lets say I have two python files. Both with an GUI. First is "Main" second is "Calculator". From Main I will start Calculator. So I have to import calculator. In Calculator I will do a calculation. Lets keep I easy an say 1+1=2. Now I want to "send" this Result to an Text in Main.

How do I do that without an circular import? I cant find an good tutorial/example for that!

My code so far:

Main:

from tkinter import *

import Test_2

window = Tk() 
window.title("First Window")

def start():
    Test_2.start_second()

Input1 = Entry(window)
Input1.grid(row=0,column=0, padx=10, pady=5)

Start = Button(window,text="Start", command=start)
Start.grid(row=1,column=0, padx=10, pady=5)

window.mainloop()

Second:

from tkinter import *


def start_second():
    window2 = Tk() 
    window2.title("Second Window")

    def send():
        x = Input.get()


    Input2 = Entry(window2)
    Input2.grid(row=0,column=0, padx=10, pady=5)

    Send = Button(window2,text="Send", command=send)
    Send.grid(row=1,column=0, padx=10, pady=5)


    window2.mainloop()

Upvotes: 0

Views: 74

Answers (1)

progmatico
progmatico

Reputation: 4964

This code does exactly what you asked for (as opposed to what I suggested in the comment; but anyway, you either get a value from a module function or you send a reference for it to alter)

I tried to follow your structure.

Basically it is a matter of sending the parent window and the first entry as parameters to the second window creation function. Don't call mainloop two times, just once in the end, and use Toplevel for all other windows after the main Tk one. This is not to say that I like the use of an inner function and of the lambda, for readability, but lambdas are necessary in tkinter everytime you want to send parameters to a command callback, otherwise it will get called right way in command definition.

tkinter_w1.py (your main.py)

from tkinter import Tk, ttk
import tkinter as tk

from tkinter_w2 import open_window_2

root = Tk()

entry1 = ttk.Entry(root)
button1 = ttk.Button(root, text='Open Window 2',
    command=lambda parent=root, entry=entry1:open_window_2(parent, entry))

entry1.pack()
button1.pack()
root.mainloop()

tkinter_w2.py (your Test_2.py)

from tkinter import Tk, ttk, Toplevel
import tkinter as tk

def open_window_2(parent, entry):

    def send():
        entry.delete(0,tk.END)
        entry.insert(0,entry2.get())

    window2 = Toplevel(parent)
    entry2 = ttk.Entry(window2)
    button2 = ttk.Button(window2, text='Send', command=send)
    entry2.pack()
    button2.pack()

Upvotes: 1

Related Questions