简体   繁体   English

如何通过同一 class 中的另一种方法将 tkinter 中的文本按钮设置为 output?

[英]How to set text button in tkinter as output from another method within same class?

I am trying to write 'improved' version of tic-tac-toe game using tkinter GUI.我正在尝试使用 tkinter GUI 编写井字游戏的“改进”版本。 I would like to use select_square() method to print out X or O on button according to button_clicked().我想使用 select_square() 方法根据 button_clicked() 在按钮上打印出 X 或 O。

from tkinter import *
from board import Board
from player import Player
from functools import partial


class BoardInterface:

    def __init__(self):
        self.all_buttons = []
        self.window = Tk()
        self.window.title("Welcome to Tic-Tac-Toe Game")
        self.choose_symbol()
        self.window.mainloop()


    def choose_symbol(self):
        self.label = Label(text="Choose X/O", font=("Arial", 20, "normal"))
        self.label.grid(row=0, column=0)
        self.button_x = Button(font=('Arial', '10'), height=5, width=10, command=lambda: self.button_clicked(self.button_x))
        self.button_x["text"] = "X"
        self.button_x.grid(row=1, column=0)
        self.button_o = Button(text="O", font=('Arial', '10'), height=5, width=10, command=lambda: self.button_clicked(self.button_o))
        self.button_o.grid(row=1, column=1)

    def button_clicked(self, button):
        if button["text"] == "X":
            self.label.config(text="X selected")
            self.button_x.destroy()
            self.button_o.destroy()
            self.print_board()
            return "x"
        else:
            self.label.config(text="O selected")
            self.button_x.destroy()
            self.button_o.destroy()
            self.print_board()
            return "o"



    def print_board(self):
        index = 0
        for i in range(1,4):
            for j in range(1,4):
                self.button = Button(text=index, font=('Arial', '10'), height=5, width=10, command=partial(self.select_square, index))
                self.button.grid(row=i, column=j)
                self.all_buttons.append(self.button)
                index += 1


    def select_square(self, index):
        print(index)
        self.bname = self.all_buttons[index]
        self.bname["text"] = "X"

Here is a bit of a hack, seems to work well...这里有点黑客,似乎运作良好......

import tkinter
import tkinter.font as tkFont
from tkinter import TclError


class App(tkinter.Tk):
    _state = 0
    _turn = False
    buttons = [[None for _ in range(3)] for _ in range(3)]

    def take_turn(self, i, j):
        button = self.buttons[i][j]
        if button['text']:
            return
        if self._turn:
            button['text'] = 'X'
        else:
            button['text'] = 'O'
        self._state = self._state + 1
        self._turn = not self._turn
        # TODO: check if game finished

    def game_reset(self, _):
        if self._state:
            self._state = 0
            self._turn = False
            for i in range(3):
                for j in range(3):
                    self.buttons[i][j]['text'] = ''
        else:
            self.destroy() # quick exit with ESC-ESC

    def game_state(self):
        pass

    def _resize(self, event):
        # main window has no master
        if event.widget.master:
            # button size change?
            return
        w, h = event.width, event.height
        # must be non-square event
        if w == h:
            return
        dim = min(w, h)
        event.widget.geometry(f'{dim}x{dim}')
        # block further processing of this event
        return "break"

    def __init__(self):
        super().__init__()
        self.title('Tic-Tac-Toe')
        self.minsize(200, 200)
        try:
            # windows only (remove the minimize/maximize button)
            # TODO: change window attributes to disable min/max
            self.attributes('-toolwindow', True)
        except TclError:
            print('Not supported on your platform')

        font = tkFont.Font(family = 'Times New Roman', size = 20)
        for i in range(3):
            self.columnconfigure(i, weight=1)
            self.rowconfigure(i, weight=1)
            for j in range(3):
                # width of one is needed to prevent button resizing with text is changed
                # text button with is in characters, image button in pixels
                button = tkinter.Button(self, width = 1, font = font,
                    command = lambda _i = i, _j = j: self.take_turn(_i, _j),
                )
                button.grid(row = i, column = j, sticky='nsew', padx = 2, pady = 2)
                self.buttons[i][j] = button
        self.bind("<Escape>", self.game_reset)
        self.bind('<Configure>', self._resize)


if __name__ == "__main__":
    app = App()
    app.mainloop()

Edit: cleaned it up, looks and responds really well now.编辑:清理它,现在看起来和响应都很好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从同一类中的另一个方法访问方法变量(Tkinter)? - How to access a method variable (Tkinter) from another method in same class? 如何在基于django类的视图中从同一个类中的另一个方法访问一个方法的变量 - how to access variable of one method from another method within the same class in django class based views 如何更改在另一个 class 中单击的按钮的文本? (Python - tkinter) - How to change the text of a button clicked in another class? (Python - tkinter) 如何使方法从Python同一类中的另一个方法获取值 - How can I make a method takes the value(s) from another method from within the same class in Python 在 Python 中的同一类中从另一个方法调用一个方法 - Calling one method from another within same class in Python 类函数的文本输出? - Tkinter - Text Output from Class function? - Tkinter 如何从另一个继承的tkinter类访问一个继承的tkinter类中的方法 - How to access a method in one inherited tkinter class from another inherited tkinter class 如何从同一个类中的另一个方法访问一个类中的方法中的变量 - How to access a variable in a method in a class from another method in the same class 在同一个类的另一个方法中调用一个类的方法的对象 - Calling an object of a method of a class within another method of the same class 如何将变量从函数传递到同一个类中的另一个变量 - how to pass a variable from a function to another within the same class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM