Python Tkinter:如何获取有关菜单操作的状态消息?

时间:2013-05-03 18:49:59

标签: python tkinter

以下内容生成一个Tkinter文本字段,其中包含一个菜单命令示例(将文本加载到文本字段中)。 应该有一个Label作为状态行,显示刚刚执行的命令。所以当点击“加载”时,我希望显示“加载文件”。 我很难将self.status收入appmenu。原因:必须首先调用app(因为self.text),但为了self.status中有app,应首先调用appmenu。没有?请帮忙。 感谢您的期待。

import Tkinter
import tkFileDialog

class App (object):
  def __init__(self, master, status):
    self.status = status
    frame = Tkinter.Frame(master)
    frame.pack(fill="both", expand=1)
    self.text_field(frame)
    self.status_line(frame)

  def status_line (self, frame):
    statusline = Tkinter.Label(frame, text = self.status)
    statusline.pack()

  def text_field(self, frame):
    self.text = Tkinter.Text(frame)
    self.text.pack(fill="both", expand=1)

class App_Menu(object):
  def __init__(self, master, text, status):
    self.text = text
    self.master = master
    menubar = Tkinter.Menu(master)
    self.menuBar = Tkinter.Menu(master)
    master.config(menu=self.menuBar)
    self.fillMenuBar(text)

  def fillMenuBar(self, text):
    self.menuFile = Tkinter.Menu(self.menuBar, tearoff=False)
    self.menuFile.add_command(label="Open",command=self.load)
    self.menuBar.add_cascade(label="File",menu=self.menuFile)

  def load(self):
    self.file=tkFileDialog.askopenfile()
    self.text.delete(1.0, Tkinter.END)
    if self.file:
      self.text.insert(1.0,self.file.read())
      self.status = "file loaded"

root = Tkinter.Tk()
status = "status"
app = App(root, status)
appmenu = App_Menu(root, app.text, status)
root.mainloop()

1 个答案:

答案 0 :(得分:2)

使用self.status = ...,您要为实例变量分配新值,但不会更改标签的文本。为此,您可以使用StringVar和set方法更改其值:

class App (object):
  # ...
  def status_line (self, frame):
    statusline = Tkinter.Label(frame, textvariable = self.status)
    statusline.pack()
  # ...

class App_Menu(object):
  def __init__(self, master, text, status):
    # ...
    self.status = status

  # ...
  def load(self):
    self.file=tkFileDialog.askopenfile()
    self.text.delete(1.0, Tkinter.END)
    if self.file:
      self.text.insert(1.0,self.file.read())
      self.status.set("file loaded")

root = Tkinter.Tk()
status = Tkinter.StringVar(root)
status.set("status")