那么,我有这个代码
main.py:
from tkinter import Tk
from tkinter import Frame
class MainWindow():
def __init__(self, master):
self.master = master
sw = self.master.winfo_screenwidth()
sh = self.master.winfo_screenheight()
w = 900
h = 600
x = (sw/2) - (w/2)
y = (sh/2) - (h/2)
self.master.geometry('%dx%d+%d+%d' % (w, h, x, y))
self.master.resizable(False, False)
#this part
self.titleFrame = Frame(root, width=w, height=h-(h*0.92), bg="#1F2123")
self.titleFrame.pack()
#this part
if __name__ == "__main__":
root = Tk()
MainWindow(root)
root.mainloop()
我想将这部分(下面)分离到另一个.py文件中,并将其导入到我原来的main.py文件
它被命名为title_frame.py:
self.titleFrame = Frame(root, width=w, height=h-(h*0.92), bg="#1F2123")
self.titleFrame.pack()
(我在原始代码中添加了注释,如果你想看看它在哪里)
至于为什么我需要一个单独的.py文件的原因,好吧(1)我需要它的代码可读性,因为我将有多个帧和(2)这是我的个人偏好。
我就是想不明白。任何帮助都将非常感激!
withquestion_import_001.py
as:
from tkinter import Tk
from tkinter import Frame
def config(self, root,w,h):
self.titleFrame = Frame(root, width=w, height=h-(h*0.92), bg="#1F2123")
self.titleFrame.pack()
和main.py
为:
from tkinter import Tk
from tkinter import Frame
from question_import_001 import config
class MainWindow():
def __init__(self, master):
self.master = master
sw = self.master.winfo_screenwidth()
sh = self.master.winfo_screenheight()
w = 900
h = 600
x = (sw/2) - (w/2)
y = (sh/2) - (h/2)
self.master.geometry('%dx%d+%d+%d' % (w, h, x, y))
self.master.resizable(False, False)
# config(self, root,w,h) # ->works !!!!!!!!!!!
# pippo = config(self, root,w,h) # ->works !!!!!!!!!!!
self.pippo = config(self, root,w,h) # ->works !!!!!!!!!!!
# #this part
# self.titleFrame = Frame(root, width=w, height=h-(h*0.92), bg="#1F2123")
# self.titleFrame.pack()
# #this part
if __name__ == "__main__":
root = Tk()
MainWindow(root)
root.mainloop()
对我来说是你最初的main.py
,但我不确定它是否有意义或有用
在main.py
中的使用:
`config(self.master, w, h)` or `pippo = config(self.master, w, h) ` or `self.pippo = config(self.master, w, h) `
andquestion_import_001.py
as:
from tkinter import Tk
from tkinter import Frame
class config(Frame):
def __init__(self, parent, w,h):
Frame.__init__(self, parent)
self.titleFrame = Frame(parent, width=w, height=h-(h*0.92), bg="#1F2123")
self.titleFrame.pack()
或:
from tkinter import Tk
from tkinter import Frame
class config(Frame):
def __init__(self, parent, w,h):
super(config,self).__init__(parent)
self.titleFrame = Frame(parent, width=w, height=h-(h*0.92), bg="#1F2123")
self.titleFrame.pack()
对我也有效