I am practicing to create a small project with different files to have a clean code. I want to show yellow frame from (fyellow.py) into (main.py) and input a label into it from (funbut.py) using Button
's function. This is my code example: (3 Python files - main.py, fyellow.py, and funbut.py)
main.py
from tkinter import * from fyellow import * import funbut root = Tk() root.geometry("500x500") # Show Yellow Frame into Main from (fyellow.py) myframe = Frameyellow(root) # Button with command - But_fun1 but1 = Button(root, text="Text",command=funbut.but_fun1) but1.pack() root.mainloop()
funbut.py
from tkinter import * from fyellow import * # Function of Button (but1) PROBLEM HERE! (ERROR - 'framey' is not defined) def but_fun1(): label1 = Label(framey,text="LabelText") label1.place(x=10,y=10)
fyellow.py
from tkinter import * class Frameyellow: def __init__(self,rootyellow): self.rootyellow = rootyellow self.framey = Frame(rootyellow, width=200,height=200,bg="yellow") self.framey.pack()
Could explain what can I do to use the self.framey
from file (fyellow.py) to avoid
error 'framey' is not defined
?
CodePudding user response:
So main.py
file would look like this:
from tkinter import Tk, Button
from fyellow import FrameYellow
from funbut import place_label
root = Tk()
root.geometry("500x500")
my_frame = FrameYellow(root)
my_frame.pack()
but1 = Button(root, text="Text", command=lambda: place_label(my_frame))
but1.pack()
root.mainloop()
fyellow.py
like this (tho kinda pointless to create a class whose sole purpose is to have the frame a different color, just use arguments and create a normal frame):
from tkinter import Frame
class FrameYellow(Frame):
def __init__(self, master, **kwargs):
super().__init__(master, **kwargs, bg='yellow')
and funbut.py
should be sth like this:
from tkinter import Label
def place_label(parent, text='Text', pos=(0, 0)):
Label(parent, text=text).place(x=pos[0], y=pos[1])
Also:
I strongly advise against using wildcard (*
) when importing something, You should either import what You need, e.g. from module import Class1, func_1, var_2
and so on or import the whole module: import module
then You can also use an alias: import module as md
or sth like that, the point is that don't import everything unless You actually know what You are doing; name clashes are the issue.