【问题标题】:Python/Tkinter dynamically update labelPython/Tkinter 动态更新标签
【发布时间】:2016-04-19 13:16:52
【问题描述】:

我目前正在尝试使用 Tkinter 为现有的 python 程序制作 GUI。该程序为用户提供了两个选项,用户必须从中选择接受或拒绝。在使用 Tkinter 之前,选项被放置在终端中并等待 raw_input。 (是/否)。我该如何做到这一点,以便画布文本使用新数据更新并等待用户按钮单击?

为了让我的问题更具体:如何在 Tkinter 主循环运行时运行另一个程序代码并使这两个程序交互?

下面的示例代码。

from Tkinter import *

root = Tk()
root.resizable(width=False, height=False)
root.geometry('{}x{}'.format(500,550))
root.wm_title("Tkinter test")

BtnFrame = Frame (root)
BtnFrame.pack(side = BOTTOM)
BtnFrame.place(y=450, x=20)

canvas_1 = Canvas(root, width = "200", height ="300")
canvas_2 = Canvas(root, width = "250", height ="300")
canvas_1.pack(side = LEFT)
canvas_2.pack(side = RIGHT)

textfield_1 = canvas_1.create_text(100,50)
textfield_2 = canvas_2.create_text(100,50,)


def update_textfiel_1(text):
   global textfield_1
   canvas_1.delete(textfield_1)
   textfield = canvas.create_text(100,50,text = text)

def update_textfiel_2(text):
   global textfield_2
   canvas_2.delete(textfield_2)
   textfield1 = canvas1.create_text(100,50,text = text)



 Accept = Button(BtnFrame, text="Accept", width=25)
 Decline = Button(BtnFrame, text="Decline", width=25)

 Accept.pack(side = LEFT)
 Decline.pack(side = RIGHT)

 root.mainloop()

【问题讨论】:

  • command 构造函数的command 选项可能是您想要的。否则eventsCanvas.bind
  • 更新后的文本会是什么?
  • 更新后的文本将是原始程序中的循环函数传递给 Tkinter 程序的内容。我试过commandCanvas.bind 都没有成功... @TadhgMcDonald-Jensen

标签: python tkinter tkinter-canvas


【解决方案1】:

首先,您的update_textfiel 函数中有一些不一致的变量名称,您可以使用.itemconfigure (documentation for methods on canvas widget) 大大简化它

def update_textfiel_1(new_text):
   canvas_1.itemconfigure(textfield_1, text=new_text)

def update_textfiel_2(new_text):
   canvas_2.itemconfigure(textfield_2, text=new_text)

如果我理解正确,您想要一种方法来获得一种功能,该功能只需等待用户按下其中一个按钮然后返回结果,tkMessageBox 很容易做到这一点:

question = """Do you accept {}?
if you say no you will instead get {}"""
#this message can GREATLY be improved
# But I really don't understand what you are using it for...

def user_confirmation(name1, name2):
    response = tkMessageBox.askyesno("Accept or Decline",question.format(name1,name2))
    print(response)
    if response: # == True
        return name1
    else:
        return name2

我还没有找到一种方法来制作适用于您当前窗口的阻塞功能...

【讨论】:

  • 我不需要 canvas_1/2 来显示文本“接受/拒绝”。我需要另一个程序来等待用户单击接受/拒绝,然后根据用户的决定继续。想象一个函数def user_confirmation(name_1,name_2): answer = raw_input("Accept/Decline") if(answer == 'Accept'): return name_1 else: return name_2。这个程序会以某种方式传递 name_1/2 以显示在 canvas_1/2 中
  • 如果这个答案对你没有帮助,那么我显然不明白你在问什么,你可能只需要使用TkMessageBox.askyesno 或类似的东西来替换你的raw_input。否则,请在您的问题中添加更多信息,例如 AcceptedDeclined 按钮实际上应该做什么。
  • 啊,对您的评论的编辑消除了我的困惑,请给我一点时间来编辑我的答案...
  • 这似乎是正确的,但原始程序呢?在 Tkinter 程序的主循环运行时它不会运行...
猜你喜欢
  • 2015-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-02
  • 1970-01-01
  • 1970-01-01
  • 2017-04-12
相关资源
最近更新 更多