tkinter GUI中不需要的括号{}

时间:2017-05-24 02:23:42

标签: python python-3.x tkinter

代码是

from tkinter import * # Import tkinter

class ChangeLabel:

    def __init__(self):

        window = Tk() # Create a window 
        window.title("Change Label Demo") # Set a title

        # Add a label to frame1
        frame1 = Frame(window) # Create and add a frame to window 
        frame1.pack()        
        self.lbl = Label(frame1, text = "No distance entered yet")
        self.lbl.pack()

        # Add a label, an entry, and a button to frame2
        frame2 = Frame(window) # Create and add a frame to window 
        frame2.pack()
        label = Label(frame2, text = "Enter a distance in kilometres:")
        self.msg = StringVar()
        entry = Entry(frame2, textvariable = self.msg) # Create entry
        btChangeText = Button(frame2, text = "Convert", 
            command = self.processButton) # Button callback method

        label.grid(row = 1, column = 1)
        entry.grid(row = 1, column = 2)
        btChangeText.grid(row = 1, column = 3)

        window.mainloop() # Create an event loop


    def processButton(self):
        calc = float(self.msg.get()) * 0.6214

        self.lbl["text"] = self.msg.get(), "Kilometres is", "%.2f" %calc, "miles"

ChangeLabel() # Create GUI 

在你输入一个数字的输出中输出

"20 {kilometres is} 12.43 miles"

如何删除{}?

2 个答案:

答案 0 :(得分:4)

而是使用str.format方法创建字符串。由于逗号,您当前创建的是tuple

self.lbl["text"] = '{} Kilometres is {:.2f} miles'.format(self.msg.get(), calc)

它发生的原因是因为小部件如何呈现元组。有关详细信息,请参阅here

答案 1 :(得分:2)

'文字'标签的属性必须是一个字符串,并且{}围绕"kilometres is"的原因是因为它在该项列表中包含一个空格。您可以使用" ".join(...)转换该项列表,将self.lbl["text"]更改为:

self.lbl["text"] = " ".join((self.msg.get(), "Kilometres is", "%.2f" %calc, "miles"))