user2918098
user2918098

Reputation: 39

Modifying a tkinter canvas from a separate class

What I want to do is create a class (Display) where I can modify the Canvas from any other class.

from tkinter import *

#--------# Main #--------#

class Main():
    def Setup(self):
        Display('makeCanvas')
        prun('Setup')

#--------# Display #--------#

class Display(object):
    def __init__(self, cmd):        
        win = Tk()
        win.geometry('500x500')
        self.winCanvas = Canvas(master=win)

        if(cmd == 'makeCanvas'):
            self.winCanvas = Canvas(width=500, height=500)
        elif(cmd == 'startLoop'):
            mainloop()
        elif(cmd == 'getCanvas'):
            self.sendCanvas()
        else:
            print('Failed')

        self.winCanvas.pack()
    def sendCanvas(self):
        return self.winCanvas

#--------# ConsolePrint #--------#

class ConsolePrint(Display, object):

    def __init__(self, text_given):
        self.tx_g = text_given
        self.totalText = ''
        self.canvas = Display('getCanvas')

 ---->  self.textFeild = self.canvas.create_text()

    def Console(self):
        print("Console")
        self.totalText += (self.tx_g + '\n')
        self.textFeild.append(text=('Console: ' + self.totalText))
        self.textFeild.pack()

class prun(object):
    def __init__(self, text_given):
        print("Printing")
        printer = ConsolePrint(str('*Running: ' + str(text_given) + '*'))
        print("Now the Console")
        printer.Console()

Main().Setup()

Its this line of code that isn't working: self.textFeild = self.canvas.create_text()

The error that comes up is: AttributeError: 'Display' object has no attribute 'create_text'

I know that I am calling for a function called 'create_text' in Display, yet I don't know how to call the Canvas method in tkinter without inheriting it. I've tried to inherit Canvas in Display, and the error I get is: TypeError: Cannot create a consistent method resolution order (MRO) for bases object, Canvas

All help is appreciated.

Upvotes: 1

Views: 490

Answers (1)

TidB
TidB

Reputation: 1759

You can directly access object attributes, in this case, you could just say

class ConsolePrint(...):
    def __init__(...):
         ...
         self.textField = self.canvas.winCanvas.create_text(0, 0, text="Whatever")

Another change I did above is that you haven't specified any parameters for create_text. You will get other errors, though, but that's not the question here.

But basically, you should rethink your script structure. It's unnecessary to create the Main and prun class and passing commands via strings are really not a good decision. Capsuling code is good, but you're overdoing a bit ;)

Upvotes: 2

Related Questions