在Python IDLE 3.7上进行简单的两键式游戏时出错,

时间:2018-11-09 13:14:59

标签: python python-3.x tkinter

我想制作一个基本游戏,其中有两个按钮“ left”和“ right”,并且我有一个角色。单击相应按钮时,角色应左右移动。这是我使用的代码。此代码未提供所需的输出。拜托,您能告诉我如何将两个按钮放在一个区域吗?还可以请您帮助使这段代码更高效吗?

from tkinter import *

class Application(Frame):

    def __init__(a, master):
        super(Application, a).__init__(master)
        a.grid()
        a.b_c = 0
        a.b = Button(a)
        a.b['text'] = "START"
        a.b['command'] = a.u
        a.b.grid()


    def u(a):
        a.b['text'] = "Move Right"
        a.b_c += 1
        print("\n"*40+" "*a.b_c+"*")

root = Tk()
root.title("Bot World")

app = Application(root)


class Applicatio(Frame):

    def __init__(x, master):
        super(Applicatio, x).__init__(master)
        x.grid()
        x.b_c = 0
        x.b = Button(x)
        x.b['text'] = "START"
        x.b['command'] = x.u
        x.b.grid()


    def u(x):
        x.b['text'] = "Move Left"
        a.b_c -= 1
        print("\n"*40+" "*a.b_c+"*")

root = Tk()
root.title("Bot World")

app = Applicatio(root)

1 个答案:

答案 0 :(得分:1)

您的代码很难遵循。请使用您的命名风格。 PEP8样式指南将对此有所帮助,并使其他人更容易阅读您的代码。

请记住,对于Python 3,您需要做的super是super().__init__()

99.9%的时间仅需要一个Tk()实例。

您可以将其合并为一个类,而不是尝试为按钮创建2个单独的类,并且可以更轻松地管理b_c类属性。

import tkinter as tk

class Application(tk.Frame):
    def __init__(self, master):
        super().__init__()
        self.b_c = 0
        self.btn1 = tk.Button(self, text="START", command=self.set_buttons)
        self.btn1.pack()

    def set_buttons(self):
        self.btn1.config(text="Move Right", command=self.move_right)
        self.btn2 = tk.Button(self, text="Move Left", command=self.move_left)
        self.btn2.pack()

    def move_right(self):
        self.b_c += 1
        print("\n" * 40 + " " * self.b_c + "*")

    def move_left(self):
        self.b_c -= 1
        print("\n" * 40 + " " * self.b_c + "*")


root = tk.Tk()
root.title("Bot World")
Application(root).pack()
root.mainloop()