Как сделать кнопку, используя тот же root, но другой файл в Tkinter? - PullRequest
0 голосов
/ 02 августа 2020

Я делаю шахматы на компьютере. Я уже закончил шахматную доску, часы и имя. Чтобы играть в шахматы, нужны фигуры. Вот чем я сейчас занимаюсь. Я хочу, чтобы шахматная фигура была в том же root, но в другом файле, чтобы минимизировать количество строк кода в одном модуле. Итак, я импортировал его следующим образом:

from ScreenDisplay import Screen

Я получил доступ к root вот так, и он работал хорошо, когда я его запускал. Я мог видеть доску, часы и имена.

self.Screen = Screen()
self.root = self.Screen.root

Я пытался добавить кнопку в этот файл, но она не появилась.

self.Character = Button(self.root, image = self.Picture)
self.Character.grid(self.root, row = y, column = x)

(Кстати , self.Picture, y и x - параметры __ init __). Как сделать так, чтобы виджеты появлялись на экране в другом модуле? Спасибо!

Вот мой весь код: ScreenDisplay.py:

"Impport time module to create clock"
import time

"Import tkinter widgets"
from tkinter import Tk
from tkinter import Label
from tkinter import Image

"Impport PIL to open images"
from PIL import ImageTk, Image


"Create chess board and timer"
class Screen:
    def __init__(self):
        "Create root"
        self.root = Tk()
        self.root.title("Chess")
        self.root.geometry("1400x700")

        "Resizing the image"
        self.Board = Image.open("ChessBoard.png")
        self.resizing = self.Board.resize((700, 700))
        self.ChessBoard = ImageTk.PhotoImage(self.resizing)

        "Putting the image in a label then putting it on the screen"
        self.ChessBoardLabel = Label(self.root, image = self.ChessBoard)
        self.ChessBoardLabel.grid(row = 0, column = 0, rowspan = 8, columnspan = 8)

        "Creating the labels and time control"
        self.AI = Label(self.root, text = 'AI', font = "Helvetica 18 bold", width = 40)
        self.AI.grid(row = 0, column = 8, columnspan = 7)

        self.Human = Label(self.root, text = "Human", font = "Helvetica 18 bold", width = 40)
        self.Human.grid(row = 7, column = 8, columnspan = 7)

        "Create time clook for both players"
        self.CountdownClock = Label(self.root, font = "Helvetica 18 bold")
        self.CountdownClock.grid(row = 0, column = 8)

        self.CountdownClock2 = Label(self.root, font = "Helvetica 18 bold")
        self.CountdownClock2.grid(row = 7, column = 8)

        "Run functions to activate the clocks"
        self.set_timer()
        self.countdown(self.CountdownClock)

        self.set_timer()
        self.countdown(self.CountdownClock2)

        "Create the loop"
        self.root.mainloop()

    def set_timer(self):
        self.t = 600
        return self.t

    def countdown(self, label):
        if self.t > 0:
            self.convert(label)
            self.t = self.t - 1
            label.after(1000, lambda: self.countdown(label))

        else:
            label.config(text = "Timer Completed")

    def convert(self, item): 
        self.seconds = self.t % (24 * 3600) 
        self.seconds %= 3600
        self.minutes = self.t // 60
        self.seconds %= 60
        item.config(text = "%02d:%02d" % (self.minutes, self.seconds))      


if __name__ == '__main__':
    board = Screen()

ChessPiece.py:

"Import the button widget from tkinter"
from tkinter import Button

"Import the Screen class from ScreenDisplay to display the pieces on the same window"
from ScreenDisplay import Screen

class ChessPiece:
    def __init__(self, x, y, picture):
        "Initialize the window here from the other file"
        self.Screen = Screen()
        self.root = self.Screen.root

        "Initialize atributes that will be used through out the code"
        self.x = x
        self.y = y
        self.Picture = picture
        self.Taken = False
        
        self.Character = Button(self.root, image = self.Picture)
        self.Character.grid(self.root, row = y, column = x)

        self.root.mainloop()


if __name__ == '__main__':
    piece = ChessPiece(2, 7, "WhiteBishop.png")
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...