2013-04-20 332 views
0

我想写一个打印出时间表的tkinter程序。要做到这一点,我必须编辑一个文本小部件将答案放在屏幕上。所有的款项相邻,没有空格,当我在它们之间增加一个空格时,在我的空白处出现了大括号。我如何摆脱那些花括号?如何在使用tkinter在python中使用空格时摆脱花括号?

P.S.这里是我的代码:

############# 
# Times Tables 
############# 

# Imported Libraries 
from tkinter import * 

# Functions 
def function(): 
    whichtable = int(tableentry.get()) 
    howfar = int(howfarentry.get()) 
    a = 1 
    answer.delete("1.0",END) 
    while a <= howfar: 
     text = (whichtable, "x", howfar, "=", howfar*whichtable, ", ") 
     answer.insert("1.0", text) 
     howfar = howfar - 1 

# Window 
root = Tk() 

# Title Label 
title = Label (root, text="Welcome to TimesTables.py", font="Ubuntu") 
title.pack() 

# Which Table Label 
tablelabel = Label (root, text="Which Times Table would you like to use?") 
tablelabel.pack (anchor="w") 

# Which Table Entry 
tableentry = Entry (root, textvariable=StringVar) 
tableentry.pack() 


# How Far Label 
howfarlabel = Label (root, text="How far would you like to go in that times table?") 
howfarlabel.pack (anchor="w") 

# How Far Entry 
howfarentry = Entry (root, textvariable=StringVar) 
howfarentry.pack() 

# Go Button 
go = Button (root, text="Go", bg="green", width="40", command=function) 
go.pack() 

# Answer Text 
answer = Text (root, bg="cyan", height="3", width="32", font="Ubuntu") 
answer.pack() 

# Loop 
root.mainloop() 

回答

0

在第15行中,您将“文本”设置为混合整数和字符串的元组。小部件期待一个字符串,而Python会很奇怪地转换它。更改该行建立自己的字符串:

text = " ".join((str(whichtable), "x", str(howfar), "=", str(howfar*whichtable), ", ")) 
+0

感谢您的回答! – 111111100101110111110 2013-04-20 13:41:51

0

在第15行,使用.format()格式化文本:

'{} x {} = {},'.format(whichtable, howfar, howfar * whichtable) 

根据文档:

字符串格式化的这种方法是Python 3中的新标准,应优先于新代码中字符串格式化操作中描述的%格式。

+0

它也适用于Python 2.6+(如果你替换为'{0} x {1} = {2},'为字符串,否则只在Python 2.7+中)。 – jorgeca 2013-04-20 11:57:27

+0

非常感谢,所有作品都很棒,并且准备好了我的作品集!!!!! – 111111100101110111110 2013-04-20 13:41:30

1

要获得自身线上的每个公式,您可能需要构建整个表作为一个字符串:

table = ',\n'.join(['{w} x {h} = {a}'.format(w=whichtable, h=h, a=whichtable*h) 
        for h in range(howfar,0,-1)]) 
answer.insert("1.0", table) 

此外,如果添加fillexpand参数answer.pack,你将能够看到更多的表格:

answer.pack(fill="y", expand=True)