我正在尝试使用Python类创建GUI。因为我是Python新手,所以我仍在学习如何排除错误。下面,我希望创建一个名为Plot\u Seismo的类,并创建一个包含列表框、退出按钮和“Plot”按钮的GUI。我在课堂上的“绘图按钮”有问题。我想要这个按钮做的是读取地震记录,然后从列表框中绘制所选的地震记录。我觉得我的语法不正确(因为我太天真)。当这个函数不在类中时,我可以让它工作,但是当我把它作为方法放在类中时,我会有点困惑。错误消息如下所示:
#!/usr/bin/env python
from Tkinter import *
from obspy.core import read
import math
class Plot_Seismo:
def __init__(self, parent):
self.master = parent
top = Frame(parent, width=500, height=300)
top.pack(side='top')
# create frame to hold the first widget row:
hwframe = Frame(top)
# this frame (row) is packed from top to bottom (in the top frame):
hwframe.pack(side='top')
# create label in the frame:
font = 'times 18 bold'
hwtext = Label(hwframe, text='Seismogram Reader GUI', font=('Arial',18,'bold'), fg="red")
hwtext.pack(side='top')
### ListBox
List1 = Listbox(root, width=50, height= 10)
List1.insert(1,"trace1.BHZ")
List1.insert(2,"trace2.BHZ")
List1.pack(padx=20, pady=20)
plot_button = Button(top, text='Plot Seismogram', command=self.plot_seis)
plot_button.pack(side='top', anchor='w', padx=45, pady=20)
self.event = read(List1.get(List1.curselection()[0]))
# finally, make a quit button and a binding of q to quit:
quit_button = Button(top, text='Quit Seismo-Reader GUI', command=self.quit)
quick_button.pack(side='top', anchor='w', padx=20, pady=20)
self.master.bind('<q>', self.quit)
def quit(self, event=None):
self.master.quit()
def plot_seis(self, event=None):
self.event.plot()
root = Tk()
Plot_Seismo = Plot_Seismo(root)
root.mainloop()
Error Message:
Traceback (most recent call last):
File "plot_seismogram.py", line 46, in <module>
Plot_Seismo = Plot_Seismo(root)
File "plot_seismogram.py", line 31, in __init__
self.event = read(List1.get(List1.curselection()[0]))
IndexError: tuple index out of range
因为我没有安装
obspy
模块,所以我不得不将您的代码缩小一点,但您应该明白这一点。你知道吗因为我的机器上只运行Python3,所以我将您的代码重写为Python3,这不是什么大事。唯一的区别应该是(
tkinter
而不是Tkinter
和print()
而不是print
)。你知道吗我更改了代码的一些部分:listbox没有使用列表填充,这使它变得更容易,并且它成为了在
plot_seis
中访问它的类属性。你知道吗由于
.curselection()
返回一个带有Listboxs项索引的元组,因此我们必须get
相应的文本项,如docs和this answer中所述。你知道吗按钮和listbox可能提供了一些事件处理特性,这些特性通过使用
self.
使listbox成为一个类属性,但它确实起到了作用:相关问题 更多 >
编程相关推荐