【发布时间】:2014-07-12 23:29:00
【问题描述】:
好的,所以我正在使用Tkinter 关注 Python GUI 的 this 教程。
我的代码如下,一切正常。然而,这是不准确的,因为该程序并没有做我真正需要的。
在 GUI 框中,我希望用户能够提供一个链接,然后该链接将用于从 urllib2 获取来自网络的一些链接,然后通过我的 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()
还有很多行我应该更改甚至删除,但我计划在我更好地理解代码及其工作原理后执行此操作。
【问题讨论】:
-
但是你已经在
Button和函数之间建立了联系(使用response = urllib2.urlopen('http://www.website.com/..')行),因为你有command=ChangeLabel -
将网址粘贴到框中并单击按钮只会提示错误。我将编辑并在我的问题中显示它。我知道两者之间已经存在联系,但不是我想要的。它一团糟
-
所以把那个放在里面
ChangeLabel -
并且总是在 python 中添加完整的错误信息。有问题的行数 - 在代码中标记该行。
-
我需要 URI 作为用户输入而不是硬编码,这是这里的主要问题。我该怎么做?
标签: python python-2.7 tkinter urllib2