在python和tkinter一起使用空白时,如何消除大括号?

2024-06-16 14:20:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个tkinter程序打印出时间表。为此,我必须编辑一个文本小部件,将答案显示在屏幕上。所有的和都是并排出现的,没有空格,当我在它们之间加一个空格时,大括号出现在我的空白处。我怎样才能摆脱那些大括号?在

注:这是我的代码:

#############
# 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 ()

Tags: totextanswergowhichtablerootlabel
3条回答

在第15行中,将“text”设置为一个由int和string混合组成的元组。小部件需要一个字符串,Python对它进行了奇怪的转换。更改该行以自己构建字符串:

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

在第15行中,使用^{}格式化文本:

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

根据文件:

This method of string formatting is the new standard in Python 3, and should be preferred to the % formatting described in String Formatting Operations in new code.

若要将每个表达式放在各自的行上,您可能需要将整个表构建为一个字符串:

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,您将能够看到更多的表:

^{pr2}$

相关问题 更多 >