简体   繁体   English

Python class 从具有列表属性的 tk.Frame 继承

[英]Python class Inheriting from tk.Frame with a list attribute

I'm in the process of teaching myself tkinter (objected-oriented style).我正在自学 tkinter(面向对象的风格)。

I want my class to produce a simple window with a single label in it.我希望我的 class 生成一个简单的 window ,其中包含一个 label。 And I want the text for the label to come from an attribute, the first element of a list.我希望 label 的文本来自一个属性,即列表的第一个元素。 This is a mockup made in Paint of what I would expect the window to look like:这是一个用 Paint 制作的模型,我希望 window 看起来像:

在此处输入图像描述

But when I run the code below I get an error message ( TypeError: create() argument 1 must be str or None, not list ).但是当我运行下面的代码时,我收到一条错误消息( TypeError: create() argument 1 must be str or None, not list )。 I can't figure out how to pass 'my_list' so to create an instance of my class.我不知道如何传递“my_list”来创建我的 class 的实例。

Thanks for any help!谢谢你的帮助!

import tkinter as tk

my_list = [222, 333, 444, 555]

class MyWindow(tk.Frame):
    def __init__(self, parent,  lst):
        self.lst = lst
        tk.Frame.__init__(self, parent)
        self.window_height = 200
        self.window_width = self.window_height * 2 
        canvas = tk.Canvas(self, width=self.window_width, height=self.window_height)
        canvas.pack()  
        label = tk.Label(self, text=str(self.lst[0]))       
        label.pack()
    
root= tk.Tk(my_list)
MyWindow(root).pack()
root.mainloop()

First, you cannot pass my_list to tk.Tk() .首先,您不能将my_list传递给tk.Tk()

Second, your MyWindow requires two parameters: parent and list (though you should name that second parameter something different).其次,您的MyWindow需要两个参数: parentlist (尽管您应该将第二个参数命名为不同的名称)。

Third, calling a geometry manager ( pack , grid , or place ) inline with the creation of the widget is a bad practice that should be avoided.第三,在创建小部件时调用几何管理器( packgridplace )是一种不好的做法,应该避免。

Here is how the final block of code should look like:以下是最终代码块的外观:

root= tk.Tk()
mywindow = MyWindow(root, my_list)
mywindow.pack()

This will end up with a window that has the label at the bottom.这将最终得到一个 window,其底部有 label。 If you want it at the top, reverse the order that you pack the items in the frame and/or explicitly state where they should go:如果您希望它位于顶部,请颠倒您在框架中打包项目的顺序和/或明确 state,它们应该是 go:

label.pack(side="top", fill="x")
canvas.pack(side="bottom", fill="both", expand=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM