我写了这段代码,但是当我运行它时,它没有显示任何错误,但是应用程序为空白,您能告诉我我做错了什么吗?谢谢
from tkinter import *
import csv
import os
os.chdir(r"C:\Users\Umer Selmani\Desktop\prog.practice\MP1")
root=Tk()
class Diet:
def __init__(self,Tops,Lefts, Rights):
self.Tops=Frame(root,width= 200,height=200).pack(side=TOP)
self.Lefts=Frame(root,width= 200,height=200).pack(side=LEFT)
self.Rights=Frame(root,width= 200,height=200).pack(side=RIGHT)
self.label1=Label(Tops,font=("ariel","bold" ,20),text="Sehir Cafeteria",
bg="darkblue").grid(row=0,columns=0)
root.mainloop()
答案 0 :(得分:2)
您需要做
diet = Diet()
diet.pack()
答案 1 :(得分:0)
如果要显示的帧,则不需要将上,左和右传递给__init__()
函数。它们是在__init__()
中创建的。
pack()
函数返回None
,这意味着您不保留对各个帧的引用。我已在示例中更正了此问题。
要显示在Diet
类中定义的框架,必须首先创建一个实例。
我对帧进行了颜色编码,以便可见。
from tkinter import *
class Diet:
def __init__(self):
self.Tops = Frame(root, width=400, height=200, bg='tan')
self.Tops.pack(side=TOP)
self.Tops.pack_propagate(False)
self.Lefts = Frame(root, width= 200, height=200, bg='salmon')
self.Lefts.pack(side=LEFT)
self.Rights = Frame(root, width= 200, height=200, bg='bisque')
self.Rights.pack(side=RIGHT)
self.label1 = Label(self.Tops, font="ariel 20 bold",
text="Sehir Cafeteria", bg="darkblue")
self.label1.pack(fill='x')
# Grid() will shrink the self.Tops frame to exactly
# fit the label.
root = Tk()
diet = Diet() # Create an instance of Diet.
root.mainloop()
其他说明
从小部件创建中得出的不同返回值取决于代码的编写方式,取决于对象之间传递信息的方式:
# The first code:
self.Tops = Frame(root, width=400, height=200, bg='tan')
# Creates a Frame and associates it with the name "self.Tops"
self.Tops.pack(side=TOP)
# uses the geometry manager pack to display the frame "self.Tops"
# The method call returns the value: None
# self.Tops is still referencing the frame
# The second code does the same thing but in a single compound statement
self.Tops = Frame(root, width=400, height=200, bg='tan').pack(side=TOP)
# Creates a frame and passes a reference to that frame to pack.
# Pack displays the label on the window and returns the value: None
# This value is given the reference "self.Tops"
尝试运行以下代码并检查控制台的打印输出。
from tkinter import *
root = Tk()
label_a = Label(root, text='A')
return_a = label_a.pack()
print('label_a:', label_a)
print('return_a:', return_a)
label_b = Label(root, text='B').pack()
print('label_b:', label_b)
root.mainloop()
希望这使事情变得更清楚。