我正在練習用不同的檔案創建一個小專案以獲得干凈的代碼。我想顯示從 ( fyellow.py ) 到 ( main.py ) 的黃色框架,并使用的函式從 ( funbut.py ) 輸入一個標簽Button。這是我的代碼示例:(3 個 Python 檔案 - main.py、fyellow.py和funbut.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)黃色.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()
可以解釋我可以做什么來使用self.framey源檔案 ( fyellow.py ) 來避免
錯誤'framey' is not defined?
uj5u.com熱心網友回復:
所以main.py檔案看起來像這樣:
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 像這樣(雖然創建一個類的唯一目的是讓框架具有不同的顏色,這有點毫無意義,只需使用引數并創建一個正常的框架):
from tkinter import Frame
class FrameYellow(Frame):
def __init__(self, master, **kwargs):
super().__init__(master, **kwargs, bg='yellow')
而funbut.py應該是某事像這樣:
from tkinter import Label
def place_label(parent, text='Text', pos=(0, 0)):
Label(parent, text=text).place(x=pos[0], y=pos[1])
另外:
我強烈建議*在匯入某些內容時不要使用通配符 ( ),您應該匯入您需要的內容,例如from module import Class1, func_1, var_2等等或匯入整個模塊:import module然后您也可以使用別名:import module as md或類似的東西,重點是不要除非您確實知道自己在做什么,否則不要匯入所有內容;名稱沖突是問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/345023.html
上一篇:tkinter串列索引超出范圍
