Tkinter按钮没有响应(没有鼠标悬停效果)

时间:2016-01-23 21:22:04

标签: python-2.7 button tkinter twisted exit

我正在编写一个游戏,其中包含从客户端到服务器以及从服务器到客户端的信息。一个特定的(非播放)客户端是监视器,它只显示游戏板和播放器。这很好用,唯一不起作用的是GUI上的退出按钮。一件小事,但我希望它能奏效。 :)另外我认为代码可能存在一些错误,即使它有效。

我尝试了各种不同的命令(sys.exit,quit ...),没有修复它。

没有错误消息,按钮根本没有任何反应。没有鼠标过度效果,如果单击它就没有任何效果。相关代码(我删除了矩阵和服务器逻辑,因为我觉得它不相关 - 如果它不是我发布的话):

class Main():
def __init__(self, master):
    self.frame = Frame(master)
    self.frame.pack()
    # Has to be counted up by server class
    rounds = 0
    # Has to be communicated by server class. If numberwin == numberrobots,
    # game is won
    numberwin = 0
    numberrobots = 2

def draw(self):
    if hasattr(self, 'info'):
        self.info.destroy()
    if hasattr(self, 'quit'):
        self.quit.destroy()
    print "Main should draw this matrix %s" % self.matrix

    [...] lots of matrix stuff [...]

    # Pop-Up if game was won
    # TODO: Make GUI quittable
    if self.numberwin == self.numberrobots:
        self.top = Toplevel()
        self.msg = Message(self.top, text="This game was won!")
        self.msg.pack(side=LEFT)
        self.quittop = Button(
            self.top, text="Yay", command=self.frame.destroy)
        self.quittop.pack(side=BOTTOM)

    # TODO: Quit GUI
    self.quit = Button(self.frame, text="Quit", command=self.frame.destroy)
    self.quit.pack(side=BOTTOM)

    # Information on the game
    self.info = Label(
        self.frame, text="Rounds played: {}, Numbers of robots in win condition: {}".format(self.rounds, self.numberwin))
    self.info.pack(side=TOP)


def canvasCreator(self, numberrows, numbercolumns):
     # Game board
    self.canvas = Canvas(
        self.frame, width=numbercolumns * 100 + 10, height=numberrows * 100 + 10)
    self.canvas.pack()


class Agent(Protocol, basic.LineReceiver):
master = Tk()
main = Main(master)
# So first matrix is treated differently from later matrixes
flagFirstMatrix = 1

def connectionMade(self):
    msg = dumps({"type": "monitor"})
    self.sendLine(msg)
    print "Sent message:", msg

def dataReceived(self, data):
    # Decode the json dump
    print "Data received: %s" % data
    data = loads(data)
    self.main.matrix = np.matrix(data["positions"])
    self.main.goals = np.matrix(data["goals"])
    self.main.next_move_by_agent = data["next_move"]
    self.main.rounds = data["rounds"]
    self.main.numberwin = data["win_states"]
    if self.flagFirstMatrix == 1:
        self.main.numberrows, self.main.numbercolumns = self.main.matrix.shape
        self.main.canvasCreator(
            self.main.numberrows, self.main.numbercolumns)
        self.main.canvas.pack()
        self.flagFirstMatrix = 0
    self.main.canvas.delete(ALL)
    self.main.draw()
    self.master.update_idletasks()
    self.master.update()

1 个答案:

答案 0 :(得分:0)

首先没有类代理的缩进,第二个退出按钮的“回调”self.frame.destroy从未被定义,所以它什么都不做。如果你的意思是tkinter destroy方法尝试self.frame.destroy()或尝试显式定义它。您也可以尝试拨打fram.pack_forget()fram.grid_forget()

根据整行代码

将master.mainloop()添加到最后一行