2017-10-28 73 views
0

附加是我在Tkinter中使用畫布構造的GUI的一部分,因此可以在背景中插入圖像。 當我調用函數Relay_1時:結果被髮送到Python shell窗口。 我想要的是畫布中的文本框,並在畫布上顯示結果(即打印結果),而不是在外殼中。 任何想法,將不勝感激。將結果打印到畫布不是殼窗口

import Tkinter 

#Function 
def Relay_1(): 
arduinoData.write(b'1') 
print ("This is a test\n") 

class ProgramGUI: 
def __init__(self): 

    # Creates the Main window for the program   
    self.main = tkinter.Tk() 

    # Change Default ICON 

    self.main.iconbitmap(self,default = 'test.ico')   

    # Create title, window size and make it a non re sizable window  
    self.main.title('Test') 
    self.main.resizable(False, False)     
    self.main.geometry('680x300')  

    self.canvas = tkinter.Canvas(self.main, width = 680, height = 300) 
    self.canvas.pack() 

    self.logo = tkinter.PhotoImage(file = 'test.png') 
    self.canvas.create_image(0,0,image = self.logo, anchor = 'nw') 

    # Create 3 Frame to group the widgets   
    self.top = tkinter.Frame(self.main) 
    self.middle = tkinter.Frame(self.main)     
    self.bottom = tkinter.Frame(self.main) 

等等等等

+0

我設置了一行代碼如下 – John

回答

1

的Tkinter的畫布組件有一個非常簡單和易於使用的方法來繪製文本稱爲create_text()。您可以使用這種方式,

self.canvas.create_text(10, 10, text='This is a test\n') 

的文本可以通過傳遞各種參數,包括fontfilljustify進行定製。檢查的通行參數的完整列表,在這裏:http://effbot.org/tkinterbook/canvas.htm#Tkinter.Canvas.create_text-method

要執行的代碼時,添加文字,您可以創建內部ProgramGUI()方法的類:

def draw_text(self, text): 
    self.canvas.create_text(10, 10, text=text) 

並創建一個對象後使用。

+0

感謝您的文本畫布代碼 - 很好地工作! - 下一步是,如何在函數執行時將文本參數的「This is a test」的打印值傳遞給文本參數? – John

+0

我已經爲你更新了答案。 – RottenCandy

+0

謝謝 - 是一個傳遞參數的函數。當我調用函數 def relay_1(): arduinoData.write(b'1') draw_text('This is a Test'),我將參數「This is a Test'傳入你建議的函數中,即def draw_text (self,text): self.canvas.create_text(10,10,text =(text)) - 我遇到的問題是我得到一個錯誤 - draw_text()缺少1所需的位置參數:'text',Am我錯誤地調用了你的函數嗎? – John