1

下面生成一个带有菜单命令示例的 Tkinter 文本字段(将文本加载到文本字段中)。应该有一个标签用作状态行,显示刚刚执行的命令。所以当点击“加载”时,我希望显示“文件加载”。我正在努力self.status进入appmenu. 原因:app必须先调用(因为self.text),但为了拥有self.statusin appappmenu应该先调用。不?请帮忙。感谢期待。

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()
4

1 回答 1

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")
于 2013-05-03T19:36:02.467 回答