Python:Tkinter按钮函数和urllib2

2024-05-14 09:25:52 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,所以我用Tkinter来跟随关于pythongui的this教程。在

我的代码在下面,一切正常。但是这并不准确,因为程序不能满足我的实际需要。在

在GUIs框中,我希望用户能够提供一个链接,然后从urllib2获取一些来自web的链接,然后通过GUI的下拉菜单打开它们。在

到目前为止,用户应该提供的链接是硬编码到源代码中的,而按钮几乎什么也不做。在

所以我需要的是能够将我的按钮与response = urllib2.urlopen连接起来?在

有什么想法吗?谢谢。在

import urllib2
from Tkinter import *
#import tkinter.messagebox
#import turtle

#fetching uris from the web
response = urllib2.urlopen('http://www.website.com/..')
html = response.read()
with open("/path/to/URIs.txt", 'w') as outfile:
    outfile.write(html)


def ChangeLabel():
    response = urllib2.urlopen('http://www.website.com/..')
    labelText.set(response)
    #yourName.delete(0, END)
    html = response.read()
    #yourName.insert(0, html)
    return

def aboutMe():
    tkinter.messagebox.showinfo('Hello there!')
    return

def openURIS():
    f = open("/path/to/URIs.txt")
    aboutStud.delete(1.0, END)

    studGradeString = ""

    for i in f:
            studGradeString += i

    aboutStud.insert(END, studGradeString)
    f.close()
    return

app = Tk()
app.title('Simple Tkinter GUI')
app.geometry('400x500')

menubar = Menu(app)
filemenu = Menu(menubar,tearoff=0)
filemenu.add_command(label="Open URIs", command=openURIS)

filemenu.add_separator()

filemenu.add_command(label="Quit", command=app.quit)
menubar.add_cascade(label="File", menu=filemenu)


helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_cascade(label="About us", command=aboutMe)
menubar.add_cascade(label="Help", menu=helpmenu)

app.config(menu=menubar)

aboutStud = Text(app)
aboutStud.insert(END, "Paste link into the little box to fetch URIs")
aboutStud.pack()

labelText = StringVar()
labelText.set('Click button below')
label1 = Label(app, textvariable=labelText, height=4)
label1.pack()

#checkBoxVal = IntVar()
#checkBox1 = Checkbutton(app, variable=checkBoxVal, text="Hello?")
#checkBox1.pack()

custom = StringVar(None)
legend = Entry(app, textvariable=custom)
legend.pack()

button1 = Button(app, text='Click to fetch URIs', width=20, command=ChangeLabel)
button1.pack(side='top', padx=15 , pady=15)

app.mainloop()

还有许多行我应该更改甚至删除,但是我计划在我更好地理解代码及其工作原理之后再这样做。在


Tags: toimportaddappresponsehtmlurllib2label

热门问题