【问题标题】:TKinter syntax to creat widgetTKinter 语法创建小部件
【发布时间】:2021-03-11 15:35:51
【问题描述】:

这在技术上写得好吗? 会不会引起什么问题。我找不到任何关于这种为 tkinter 构建代码的方式的信息,但是它可以工作..

myButton = tkinter.Button(main_window)
myButton['text'] = "Click Me!"
myButton['state'] = "normal"
myButton['command'] = myClick
myButton['fg'] = "blue"

代替:

myButton = tkinter.Button(main_window,text="Click Me!",state="normal", command=myClick,fg="blue")

如果有人想为什么,只是因为代码在我看来更整洁。

【问题讨论】:

  • 是的,它会起作用,但最好换一种方式练习
  • 是的,技术上没问题,但你会为每个小部件都这样做吗?这意味着您将拥有如此多的代码行。

标签: python python-3.x python-2.7 tkinter tk


【解决方案1】:

你写的东西会起作用,但如果你不喜欢标准语法的呈现,你总是可以这样做:

myButton = tkinter.Button(main_window,
                      text="Click Me!",
                      state="normal",
                      command=myClick,
                      fg="blue")

【讨论】:

    【解决方案2】:

    根据the docs,这是配置小部件的合法方式。

    之所以可行,是因为 tkinter 使用了mapping protocol。作为一个例子,你可以在这里看到它是如何工作的,并且使用它没有危险:

    class Unpackable(object):
        def __init__(self):
            self.options=['hello','world']
        def keys(self):
            return self.options
        def __getitem__(self, key):
            return dict(zip(self.options,'first_word last_word'.split()))[key]
        
    unp = Unpackable()
    print(unp['hello'])
    

    输出:

    first_word
    

    官方 python 文档告诉setting options

    选项控制小部件的颜色和边框宽度等内容。 可以通过三种方式设置选项:

    在对象创建时,使用关键字参数

    fred = Button(self, fg="red", bg="blue")
    

    创建对象后,将选项名称视为字典 索引

    fred["fg"] = "red"
    fred["bg"] = "blue"
    

    使用 config() 方法更新对象后面的多个属性 创作

    fred.config(fg="red", bg="blue")
    

    【讨论】:

      【解决方案3】:

      这是正确的。我的意思是说你刚刚定义了按钮的变量然后你正在添加按钮的属性 以下方式仅在一个语句中调用所有属性。 myButton = tkinter.Button(main_window,text="Click Me!",state="normal",command=myClick,fg="blue")

      但是你已经通过变量调用了所有属性。它只需要更多的行。

      从技术上讲,你写的很好

      【讨论】:

      • 那会怎样:myButton.text="examplestring" ???好像不行。
      • 其实这是我的错 myButton.(attributes) 为 pack() place() 和 greed() 工作而不是任何其他。你所做的主要是用来设计一个窗口
      猜你喜欢
      • 1970-01-01
      • 2021-04-12
      • 2015-02-06
      • 1970-01-01
      • 2015-01-27
      • 2011-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多