2013-04-20 35 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) 
相關問題