如何将列表中的随机输出居中?

时间:2015-07-14 02:22:04

标签: python python-2.7 tkinter

from Tkinter import *
import random
from PIL import Image

movies = (open('C:\Users\Me\Desktop\Projects\movies.txt').readlines())
mymovie = (movies)
print(mymovie)

def pickMovie():
    movieLabel.configure(text=random.choice(movies))

#GUI Window
root = Tk()
root.title('Movie Randomizer')
root.geometry('900x800')

#picture
photo = PhotoImage(file='C:\Users\Sivang\Desktop\Projects\popcorn.gif')

label = Label(image=photo)
label.image = photo # this is my reference bitch
label.pack()

#Movie Label
movieLabel = Label(root, text="", font=('Times New Roman', 28))
movieLabel.pack()

#Pick Movie
pickButton = Button(text="Pick!", fg="red", bg="white", command=pickMovie)
pickButton.pack(side='bottom', padx = 5, pady = 25)

#start the GUI
root.mainloop()

我的问题涉及以下代码:

movies = (open('C:\Users\Me\Desktop\Projects\movies.txt').readlines())
mymovie = (movies)
print(mymovie)

每当我运行程序时,文本都不在中心。我的问题是我如何始终把它放在中心位置。

1 个答案:

答案 0 :(得分:1)

使用str.format您可以指定右对齐,左对齐或居中对齐,请参阅Format Specification Mini-Language

示例:

movies = "star wars\nsome awesome movie\nanother great movie\nmeh movie"
>>> print movies
star wars
some awesome movie
another great movie
meh movie

现在使用.format并指定中心与特定宽度对齐,我们得到:

>>> print '\n'.join('{:^50}'.format(s) for s in movies.split('\n'))
                    star wars                     
                some awesome movie                
               another great movie                
                    meh movie    

你可以添加一些天赋:

>>> print '\n'.join('{:-^50}'.format(s) for s in movies.split('\n'))
--------------------star wars---------------------
----------------some awesome movie----------------
---------------another great movie----------------
--------------------meh movie---------------------

您很可能必须使用宽度来确保字符串居中。