【问题标题】:Using python class with tkinter将 python 类与 tkinter 一起使用
【发布时间】:2014-08-13 12:17:55
【问题描述】:

根据我的阅读,将 GUI 的代码包装在一个类中是最佳实践。我该怎么做呢?我根据我看过的一些示例提出了以下代码,但这不起作用,因为 DropdownMenu 显然没有定义?我已经成功使用了这个函数,没有类包装。

import Tkinter as tk
import tkFileDialog
import os

class Window(tk.Frame):

  def DropdownMenu(options,status,name):
    optionFrame = tk.Frame(root)
    optionLabel = tk.Label(optionFrame)
    optionLabel["text"] = name
    optionLabel.pack(side=LEFT)
    var = StringVar(root)
    var.set(status)
    w = tk.OptionMenu(optionFrame, var, *options)
    w.pack(side=LEFT)
    optionFrame.pack()
    return w

  def __init__(self,parent):
    tk.Frame.__init__(self,parent)

    ndim_options = DropdownMenu(("1","2","3"),'-',"Number of dimensions")


if __name__ == "__main__":
  root = tk.Tk()
  Window(root).pack()
  root.mainloop()

【问题讨论】:

    标签: python user-interface tkinter


    【解决方案1】:

    当你调用 DropdownMenu(在类内)时,使用 self ...

    ndim_options = self.DropdownMenu((...
    

    【讨论】:

    • 这给了我另一个错误 - 显然 DropdownMenu 从某个地方获得了一个额外的参数? ndim_options = self.DropdownMenu(("1","2","3"),'-',"Number of indirect dimensions") TypeError: DropdownMenu() takes exactly 3 arguments (4 given)
    • 这又是self,使用def DropdownMenu(self, options, status, name):
    • 运行到optionLabel.pack(side=LEFT),但我收到错误optionLabel.pack(side=LEFT) NameError: global name 'LEFT' is not defined ?
    • 那是因为您将from Tkinter import * 更改为import Tkinter as tk。 LEFT 在 Tkinter 中定义,所以你现在应该使用tk.LEFT。 StringVar 也是如此。
    猜你喜欢
    • 2015-11-14
    • 2015-11-27
    • 2020-02-12
    • 1970-01-01
    • 1970-01-01
    • 2016-06-20
    • 1970-01-01
    • 2010-09-18
    相关资源
    最近更新 更多