简体   繁体   中英

How can I get rid of curly braces when using white space in python with tkinter?

I am trying to write a tkinter program that prints out times tables. To do this, I have to edit a text widget to put the answer on the screen. All of the sums come up right next to each other with no spaces, when I add a space between them, curly braces appear around my white space. How ca I get rid of those curly braces?

PS Here is my code:

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

To get each equation on its own line, you might want to build the whole table as one string:

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)

Also, if you add fill and expand parameters to answer.pack , you will be able to see more of the table:

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

In line 15, you set "text" to a tuple of mixed ints and strings. The widget is expecting a string, and Python converts it oddly. Change that line to build the string yourself:

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

In line 15, use .format() to format your text:

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

According to the docs:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM