Python Forum

Full Version: How to work with multiple files and tkinter?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a beginners question about importing files and not being able to use a function in this file because it can't 'look back'.

I have two files. main.py:
from tkinter import *
from function import drawLine
master = Tk()

canvas_width = 80
canvas_height = 40
w = Canvas(master, 
           width=canvas_width,
           height=canvas_height)
w.pack()

y = int(canvas_height / 2)

drawLine()

mainloop()
and function.py:
def drawLine():
	w.create_line(0, y, canvas_width, y, fill="#476042")
I understand that 'function.py' cannot look into 'main.py'. How to write a function in 'function.py' that draws a line in the 'main.py' canvas? I hope someone can teach me about the way people work usually with drawing something on a canvas that is in another file :)
Define the function so that it takes arguments and pass those when you call it.
Aahh Thank you for the sugestion! :) After a lot of trying I found a way to do what I want.

main.py:
from tkinter import *
from function import drawLine

master = Tk()
w = Canvas(master, 
           width=80,
           height=40)
w.pack()

drawLine(10, 10, 100, 10, w)

mainloop()
function.py:
def drawLine(x1, y1, x2, y2, w):
	w.create_line(x1, y1, x2, y2)
But having said that, do you really need the function in the first place? I mean, it doesn't really give you anything in this case, other than one unnecessary level of indirection.