python 開啟一個檔案並隨機讀取檔案某一行
阿新 • • 發佈:2019-02-20
#!/usr/bin/python2.6 # -*- coding: utf-8 -*- import Tkinter import tkMessageBox import random import time from FileDialog import * class Application(Frame): #Frame所有Widget的父容器 def __init__(self, master=None): Frame.__init__(self, master) #如果子類的構造方法中沒有顯示的呼叫基類構造方法,則系統預設呼叫基類無引數的構造方法,而基類中又沒有預設無參的構造方法,則編譯出錯。而且子類的建構函式,可能與父類的引數個數、順序都不一致,無法推測出應該如何呼叫父類的建構函式。所以需要手動呼叫父類建構函式。 #self.master=master #master.geometry('400x400') self.pack() #pack()方法把Widget加入到父容器中,並實現佈局。pack()是最簡單的佈局. self.createWidgets() self.fh2="null" def createWidgets(self): self.name = StringVar() self.name.set("123") self.helloLabel = Label(self, textvariable=self.name) self.helloLabel.pack() self.alertButton = Button(self, text='Open', command=self.inputnumber) self.alertButton.pack(side=LEFT) #定義停靠在父元件的哪一邊上,“top”, “bottom”, “left”, “right”,(預設為”top”) self.startButton = Button(self, text='Start', command=self.randomStart) self.startButton.pack(side=LEFT) self.endButton = Button(self, text='End', command=self.randomStop) self.endButton.pack(anchor="w") #對齊方式,左對齊”w”,右對齊”e”,頂對齊”n”,底對齊”s” def inputnumber(self): fd = LoadFileDialog(self) filename = fd.go() # 顯示開啟檔案對話方塊,並獲取選擇的檔名稱 with open(filename,'r') as f: self.fh2=f.readlines() def randomStart(self): self.n=1 while self.n==1: #num = random.randint(12, 20) num = random.choice(self.fh2) time.sleep(0.1) self.update() self.name.set(num) if self.n==0: break def randomStop(self): self.n=0 app = Application() # 設定視窗標題: app.master.title('Random') # 主訊息迴圈: app.mainloop()