我正在编写一个连接到reddits API的程序。我为用户设置了三个输入小部件,以输入特定的单词,特定的subreddit和特定的要解析的帖子数。
下面是代码。我所有这些都坐在一个名为KDGUI的类中。运行脚本时,我只会得到空白的Tkinter GUI屏幕。
有什么想法吗?我尝试在类中来回切换GUI代码。我还没有足够的经验来真正解决这个问题。
谢谢!
这是关于Sublime Text的。我没有发布API信息,但可以想象它在根变量之上。
root = tk.Tk()
Ht = 300
Wd = 450
class KDGUI():
def enter_info():
word = e1.get()
subred = e2.get()
amnt = e3.get()
def run_bot():
sub = r.subreddit(subred)
time.sleep(1)
print("---Grabbing subreddit---\n")
time.sleep(1)
subs = sub.top('day', limit=amnt)
print("---Grabbing posts in sub---\n")
time.sleep(1)
print("Looking for Articles..\n")
word_not_found = True
for posts in subs:
article_url = posts.url
post_title = posts.title
word_to_find = word
word_not_found = False
if word_to_find in post_title:
time.sleep(3)
print(post_title)
print('')
else:
word_not_found = word_not_found and True
if word_not_found:
print("Can't find articles in the subreddit!")
root.title("Finding Kawhi Articles")
canvas = tk.Canvas(root, height=Ht, width=Wd)
canvas.pack()
background_image = tk.PhotoImage(file='Kawhi-Leonard.gif')
background_label = tk.Label(root, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
e1 = tk.Entry(root) # Word to enter
e1.place(relx=.275, rely=.45)
e2 = tk.Entry(root) # subreddit to enter
e2.place(relx=.275, rely=.55)
e3 = tk.Entry(root) # sort by amount of posts
e3.place(relx=.275, rely=.65)
activate_button = tk.Button(root, text="Click here to generate
article!", command=run_bot)
activate_button.place(relx=.20, rely=.85, relwidth=0.55,
relheight=0.10)
close_button = tk.Button(root, text="Click to close program",
command = root.quit)
close_button.place()
root.resizable(False, False)
root.mainloop()
KDGUI()
答案 0 :(得分:0)
由于您选择的是OOP方法,因此您需要首先创建您的类的实例,然后调用该方法以创建窗口小部件,因为它没有__init__
,如下所示:
root = tk.Tk()
Ht = 300
Wd = 450
class KDGUI():
def enter_info(self):
...
kd = KDGUI()
kd.enter_info()
root.mainloop()
但是我建议您通过继承Tk
或Frame
来更好地组织GUI,如下所示:
import tkinter as tk
root = tk.Tk()
class MainFrame(tk.Frame):
def __init__(self, master=None, **kwargs):
tk.Frame.__init__(self, master, **kwargs)
self.entry1 = tk.Entry(self)
self.entry2 = tk.Entry(self)
self.button = tk.Button(self,text="Print entry values",command=self.get_entry_values)
for i in (self.entry1, self.entry2, self.button):
i.pack()
def get_entry_values(self):
print (self.entry1.get(), self.entry2.get())
main = MainFrame(root)
main.pack()
root.mainloop()
这将使您的GUI易于维护。