Python / Tkinter动态更新标签

时间:2016-04-19 13:16:52

标签: python tkinter tkinter-canvas

我目前正在尝试使用Tkinter为现有的python程序创建GUI。该程序为用户提供了两个选项,用户必须从中选择接受或拒绝。在使用Tkinter之前,选项被放置在终端中并等待raw_input。 (Y / N)。我怎样才能使画布文本更新为新数据并等待用户按钮单击?

使我的问题更具体:如何在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()

1 个答案:

答案 0 :(得分:0)

首先,您的update_textfiel函数中存在一些不一致的变量名称,您可以使用.itemconfiguredocumentation 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

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