创建GUI时遇到麻烦

时间:2019-12-03 18:29:01

标签: python user-interface tkinter

我正在从事计算机科学作业,但遇到麻烦,任务是使用一个按钮创建gui,该按钮会打开一个新窗口并显示Swapi API(位于www.swapi.co上)的信息,我的问题是它说我缺少位置争论,并且无法使用tkinter模块找出它们在哪里丢失或我为Gui im做错了什么,我也正在导入一个类,我将该程序和该类都放在下面

from tkinter import *
from People import Person

def FormatToString(collection):
        results = ""

        for item in collection:
            response = requests.get(item)
            dataRow = response.json()
            results += " {}, ".format(dataRow['name'])

        return results

def GetHomeWorld(homeworld):
        response2 = requests.get(homeworld)
        Json_data2 = response2.json()
        homeworld = Json_data2['name']
        return homeworld

root = Tk()
root.title('A visual Dictionary of the Star Wars Universe')
root.geometry('{}x{}'.format(460, 350))

# layout all of the main containers
root.grid_rowconfigure(1, weight=1)
root.grid_columnconfigure(0, weight=1)

# create all of the main containers
top_frame = Frame(root, bg='cyan',padx=100, pady=8)
center = Frame(root, bg='gray', padx=3, pady=3)

top_frame.grid(row=0, sticky="ew")
center.grid(row=1, sticky="nsew")

# create the widgets for the top frame
model_label = Label(top_frame, text='Filter Example')
width_label = Label(top_frame, text='Filter by keyword:')
entry_W = Entry(top_frame, background="pink")
def DataFilter():
    root.title(entry_W.get())
    center.destroy()
button = Button(top_frame, text="Submit", command=DataFilter)

# layout the widgets in the top frame
model_label.grid(row=0, columnspan=3)
width_label.grid(row=1, column=0)
entry_W.grid(row=1, column=1)
button.grid(row=1, column=2)


import json 
import requests

starAPI = "https://swapi.co/api/people/"
response = requests.get(starAPI)
json_data = response.json()



i = 1
Label(center, text= 'StarShips\n=========',  width=20, pady=13, padx=13).grid(row=1, column = 0)
Label(center, text= 'Name\n=====', width=20, pady=13, padx=13).grid(row=1, column = 1)
Label(center, text= 'Birth Year\n==========', width=20, pady=13, padx=13).grid(row=1, column = 2)
Label(center, text= 'Gender\n======', width=10, pady=13, padx=13).grid(row=1, column = 3)
Label(center, text= 'Eye Color\n=========', width=15, pady=13, padx=13).grid(row=1, column = 4)
Label(center, text= 'Homeworld\n========',  width=15, pady=13, padx=13).grid(row=1, column = 5)


for person in (json_data['results']):
    name = str(person['name'])
    birth_year = str(person['birth_year'])
    gender = str(person['gender'])
    eye_color = str(person['eye_color'])
    homeworld = GetHomeWorld(person['homeworld'])
    starships = FormatToString(person['starships'])
    i += 1
    Button(center, text = 'Click Me for StarShips', width = 20, pady = 13, padx = 13, bg = 'black', fg = 'white', command = Person.openwindow(starships)).grid(row=i, column = 0)
    Label(center, text= name, width=20, pady=13, padx=13).grid(row=i, column = 1)
    Label(center, text= birth_year, width=20, pady=13, padx=13).grid(row=i, column = 2)
    Label(center, text= gender, width=10, pady=13, padx=13).grid(row=i, column = 3)
    Label(center, text= eye_color, width=15, pady=13, padx=13).grid(row=i, column = 4)
    Label(center, text= homeworld,  width=15, pady=13, padx=13).grid(row=i, column = 5

root.mainloop()

=====================================================================================================

import json
import requests
from tkinter import *

class Person():
    def __init__(self, name, birth_year, eye_color, gender, homeworld, starships):
        self.name = name
        self.birth_year = birth_year
        self.eye_color = eye_color
        self.gender = gender
        self.starships = self.FormatToString(starships)
        self.homeworld = self.GetHomeWorld(homeworld)

    def FormatToString(self, collection):
        results = ""

        for item in collection:
            response = requests.get(item)
            dataRow = response.json()
            results += " {} |".format(dataRow['name'])

        return results

    def GetHomeWorld(self, homeworld):
        response2 = requests.get(homeworld)
        Json_data2 = response2.json()
        homeworld = Json_data2['name']
        return homeworld

    def openwindow(self, starships):
        window = Tk()
        window.geometry('{}x{}'.format(460, 350))
        window.title('Starships')


        # layout all of the secondary containers
        window.grid_rowconfigure(1, weight=1)
        window.grid_columnconfigure(0, weight=1)

        # create all of the secondary containers
        top_frame2 = Frame(window, bg='cyan',padx=100, pady=8)
        center2 = Frame(window, bg='gray', padx=3, pady=3)

        top_frame2.grid(row=0, sticky="ew")
        center2.grid(row=1, sticky="nsew") 

        Label(center2, text= starships,  width=30, pady=13, padx=13).grid(row=0, column = 0)

        window.mainloop


    def __str__(self):
        return "Name: {}\nBirth year: {}\nGender: {}\nEye Color: {}\nStarships: {}\nHomeworld: {}".format(self.name, self.birth_year, self.gender, self.eye_color, self.starships, self.homeworld)

1 个答案:

答案 0 :(得分:0)

如果使用Person.openstarship(starship),则将其作为静态方法而不是类方法运行,因此它不使用self,并且会告知您缺少值。

您应该使用装饰器@staticmethod并删除self

    @staticmethod
    def openwindow(starships):

或者您将不得不创建类Person的实例

person_instance = Person(...put values...)
Button(..., command=person_instance.openwindow(starship))

但是command=还有其他错误。它需要没有()arguments and later it will use()to run this function. To assign method with argument you can use lambda`的函数名。

Button(..., command=lambda:person_instance.openwindow(starship))

但是在循环创建的command=中使用参数需要使用新变量来复制原始变量的访问权限,该原始变量将在下一个循环中被覆盖

Button( command=(lambda x=starships:Person.openwindow(x)) )

其他问题:GUI应该只有一个用Tk()创建的主窗口。要创建其他窗口,请使用Toplevel()。在其他GUI框架中可以类似。

所有GUI框架都使用主循环(也称为event loop),并且在所有GUI框架中应仅是一个主循环-在tkinter中,它是tkinter.mainloop()


还有其他建议,但它们不是错误:

  • import *不是首选,最好使用import tkinter或非常流行的import tkinter as tk。然后,您必须使用tk.Tk()tk.Button()等。

  • 方法/功能应具有lower_case_names-即get_home_world() format_to-string

您可以在PEP 8 -- Style Guide for Python Code

中看到的所有建议
import json
import requests
from tkinter import *

class Person():

    def __init__(self, name, birth_year, eye_color, gender, homeworld, starships):
        self.name = name
        self.birth_year = birth_year
        self.eye_color = eye_color
        self.gender = gender
        self.starships = self.FormatToString(starships)
        self.homeworld = self.GetHomeWorld(homeworld)

    def FormatToString(self, collection):
        results = ""

        for item in collection:
            response = requests.get(item)
            dataRow = response.json()
            results += " {} |".format(dataRow['name'])

        return results

    def GetHomeWorld(self, homeworld):
        response2 = requests.get(homeworld)
        Json_data2 = response2.json()
        homeworld = Json_data2['name']
        return homeworld

    @staticmethod
    def openwindow(starships):
        window = Toplevel()
        #window.geometry('460x350')
        window.title('Starships')


        # layout all of the secondary containers
        window.grid_rowconfigure(1, weight=1)
        window.grid_columnconfigure(0, weight=1)

        # create all of the secondary containers
        top_frame2 = Frame(window, bg='cyan',padx=100, pady=8)
        center2 = Frame(window, bg='gray', padx=3, pady=3)

        top_frame2.grid(row=0, sticky="ew")
        center2.grid(row=1, sticky="nsew") 

        Label(center2, text= starships,  width=30, pady=13, padx=13).grid(row=0, column = 0)

        #window.mainloop()


    def __str__(self):
        return "Name: {}\nBirth year: {}\nGender: {}\nEye Color: {}\nStarships: {}\nHomeworld: {}".format(self.name, self.birth_year, self.gender, self.eye_color, self.starships, self.homeworld)

from tkinter import *

def FormatToString(collection):
        results = ""

        for item in collection:
            response = requests.get(item)
            dataRow = response.json()
            results += " {}, ".format(dataRow['name'])

        return results

def GetHomeWorld(homeworld):
        response2 = requests.get(homeworld)
        Json_data2 = response2.json()
        homeworld = Json_data2['name']
        return homeworld

root = Tk()
root.title('A visual Dictionary of the Star Wars Universe')
#root.geometry('460x350')

# layout all of the main containers
root.grid_rowconfigure(1, weight=1)
root.grid_columnconfigure(0, weight=1)

# create all of the main containers
top_frame = Frame(root, bg='cyan',padx=100, pady=8)
center = Frame(root, bg='gray', padx=3, pady=3)

top_frame.grid(row=0, sticky="ew")
center.grid(row=1, sticky="nsew")

# create the widgets for the top frame
model_label = Label(top_frame, text='Filter Example')
width_label = Label(top_frame, text='Filter by keyword:')
entry_W = Entry(top_frame, background="pink")
def DataFilter():
    root.title(entry_W.get())
    center.destroy()
button = Button(top_frame, text="Submit", command=DataFilter)

# layout the widgets in the top frame
model_label.grid(row=0, columnspan=3)
width_label.grid(row=1, column=0)
entry_W.grid(row=1, column=1)
button.grid(row=1, column=2)


import json 
import requests

starAPI = "https://swapi.co/api/people/"
response = requests.get(starAPI)
json_data = response.json()

print(json_data)

i = 1
Label(center, text= 'StarShips\n=========',  width=20, pady=13, padx=13).grid(row=1, column = 0)
Label(center, text= 'Name\n=====', width=20, pady=13, padx=13).grid(row=1, column = 1)
Label(center, text= 'Birth Year\n==========', width=20, pady=13, padx=13).grid(row=1, column = 2)
Label(center, text= 'Gender\n======', width=10, pady=13, padx=13).grid(row=1, column = 3)
Label(center, text= 'Eye Color\n=========', width=15, pady=13, padx=13).grid(row=1, column = 4)
Label(center, text= 'Homeworld\n========',  width=15, pady=13, padx=13).grid(row=1, column = 5)


for person in (json_data['results']):
    name = str(person['name'])
    birth_year = str(person['birth_year'])
    gender = str(person['gender'])
    eye_color = str(person['eye_color'])
    homeworld = GetHomeWorld(person['homeworld'])
    starships = FormatToString(person['starships'])
    i += 1
    Button(center, text = 'Click Me for StarShips', width = 20, pady = 13, padx = 13, bg = 'black', fg = 'white', command=lambda x=starships:Person.openwindow(x)).grid(row=i, column = 0)
    Label(center, text= name, width=20, pady=13, padx=13).grid(row=i, column = 1)
    Label(center, text= birth_year, width=20, pady=13, padx=13).grid(row=i, column = 2)
    Label(center, text= gender, width=10, pady=13, padx=13).grid(row=i, column = 3)
    Label(center, text= eye_color, width=15, pady=13, padx=13).grid(row=i, column = 4)
    Label(center, text= homeworld,  width=15, pady=13, padx=13).grid(row=i, column = 5)

root.mainloop()