2016-03-04 81 views
2

我想提出一個隨機的網站生成器上運行,從蟒蛇一個exe,我試圖讓這個當您單擊按鈕,生成它也打開你的瀏覽器,但一切的聯繫,我覺得對互聯網將無法工作。 這是我的代碼,我真的很感謝一些幫助。如何使用Tkinter的按鈕

from tkinter import * 
import random 
import tkinter as tk 
from tkinter import ttk 
import os 
NORM_FONT=("timesnewroman", 12) 
root = Tk() 
class Window(Frame): 
    def showtxt(self): 
     text=Label(self, text="Please change the file location after os.startfile to the directory of your browser including the browser exe itself") 

    def openFile(self): 
     os.startfile("C:\Program Files (x86)\Mozilla Firefox\firefox") 



    def __init__(self, master=None): 
     Frame.__init__(self, master)     
     self.master = master 
     self.init_window() 


    def init_window(self): 

     self.showtxt 


     self.master.title("Random Website Generator") 


     self.pack(fill=BOTH, expand=1) 


     quitButton = Button(self, command = self.openFile, text="Generate URL", bg = "#009933") 

     quitButton.configure(command = lambda: popupmsg ("Please check the shell or command prompt for the URL. And please change the file location after os.startfile to the directory of your browser including the browser .exe itself")) 

     quitButton.bind('<ButtonRelease-1>', self.client_exit,) 

     quitButton.place(x=150, y=130) 

    def client_exit(self, event=None): 
     File = open("Random Website.txt",).readlines() 
     name=random.choice(File)[:-1] 
     print (name) 




def popupmsg(msg): 
    popup = tk.Tk() 
    popup.wm_title("Name Generator") 
    label = ttk.Label(popup, text=msg, font=NORM_FONT) 
    label.pack(side="top", fill="x", pady=10) 
    B1 = ttk.Button(popup, text="OK", command = popup.destroy) 
    B1.pack() 
    popup.mainloop() 






root.geometry("400x300") 

app = Window(root) 
root.mainloop() 

回答

2

我想象你的代碼是提高WindowsError: [Error 2] The system cannot find the file specified: 'C:\\Program Files\\Mozilla Firefox (x86)\x0cirefox'。特別是,注意到這個錯誤是應該\f\x0c

你需要躲避反斜槓在你的文件的路徑,否則你會在不知不覺中引用轉義序列\f

os.startfile("C:\\Program Files (x86)\\Mozilla Firefox\\firefox") 

或者,您可以使用raw string

os.startfile(r"C:\Program Files (x86)\Mozilla Firefox\firefox") 
+0

或者在文件名中使用正斜槓,即使在Windows上也是如此,並避免反斜槓問題。 –