程序有时会从文本文件输出空白,我该怎么做呢?

时间:2017-08-01 12:36:48

标签: python tkinter

我有这个代码是一个未来的程序,它是一个非常简单的程序,它有两个按钮,一个重置和一个实际上让你的未来的按钮。然后它有一个标签,供您将来输出。我从文本文件导入文本,但是当你运行程序时,我有时会从文本文件中删除空白,我该如何阻止它。

代码非常简单,因为我是python和tkinter的新手,我只是在构建一些程序来建立我的知识。对此问题的任何帮助都会有很大的帮助,谢谢

from tkinter import*
import random

window =Tk()



#static properties
window.title("Your Future")
window.resizable(0,0) # this stop the window from being able to be resized

#Things in the application
Label1 = Label(window, relief = 'groove', width = 100, height  = 2)
FutureButton = Button(window)
ResetButton = Button(window)

#text in button
FutureButton.configure(text = "Get your Furture")
ResetButton.configure(text = "Reset")
ResetButton.configure(state = DISABLED)

#dynamic properties
def pick():
    with open("Future.txt") as f:
        lines = f.readlines()
        test = (random.choice(lines))
        print(test)
    if test ==():
        test = ("You wil get old and die alone")
    Label1.configure(text = test)
    FutureButton.configure(state = DISABLED)
    ResetButton.configure(state = NORMAL)

def reset():
    Label1.configure(text = "..........")
    FutureButton.configure(state = NORMAL)
    ResetButton.configure(state = DISABLED)

FutureButton.configure(command = pick)
ResetButton.configure(command = reset)

#Placing shit
Label1.grid(row = 1, column = 1, columnspan = 10,)
FutureButton.grid(row = 2, column = 5, rowspan = 3)
ResetButton.grid(row = 3, column = 6, rowspan = 2,)

window.mainloop()

1 个答案:

答案 0 :(得分:0)

阅读以下行时,请使用rstrip()忽略空行:

def pick():
    with open("Future.txt") as f:
        lines = filter(None, (line.rstrip() for line in f))
        test = (random.choice(lines))
        print(test)
    if test ==():
        test = ("You wil get old and die alone")
    Label1.configure(text = test)
    FutureButton.configure(state = DISABLED)
    ResetButton.configure(state = NORMAL)

方法rstrip()返回字符串的副本,其中所有字符都已从字符串末尾删除(默认空格字符)。