簡體   English   中英

創建 GUI 時遇到問題

[英]having trouble with creating a GUI

我正在做計算機科學作業並且遇到了問題,任務是創建一個帶有按鈕的 gui,該按鈕打開一個新窗口並顯示來自 Swapi API(在 www.swapi.co 上找到)的信息,我的問題是它說 im缺少位置論證並且無法弄清楚它們丟失的地方或我使用 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)

如果您使用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函數名arguments and later it will use () to run this function. To assign method with argument you can 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框架應該只有一個主循環-在tkintertkinter.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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM