简体   繁体   中英

How to call text from a function and print it on Tkinter GUI?

I have a scenario where I need to fetch some text and print it inside the Tkinter GUI canvas when a button is pressed.

The code inside the function looks as follows:

def plot_best_batsmen():
    print("The best Batsman of the Tournament could possibly be: ",
          dataset.loc[dataset.loc[dataset['Innings']>=15,'Average'].idxmax(),'Names'])

The code for the button is as follows:

b5 = Button(root, text="Best Batsmen", command=plot_best_batsmen, bg="#34495E", fg="white").pack(side = LEFT)

My expected result is to print the name of the player along with an image on the Tkinter GUI when the button is clicked. But when I run the code on Anaconda, it's printing the name on the console instead of printing inside the GUI.

Can anyone please help me in solving this problem?

Use canvas.create(x,y, text=' ' anchor='nw) in the function. Label() can also be used.

I assume you have defined Canvas already before the function

Here is an example.

from tkinter import *

root = Tk()

canvas = Canvas(root)
canvas.pack()

def plot_best_batsmen():
    text = "The best Batsman of the Tournament could possibly be: ", dataset.loc[dataset.loc[dataset['Innings']>=15,'Average'].idxmax(),'Names']
    canvas.create_text(1, 1, text=text, anchor='nw')

b5 = Button(root, text="Best Batsmen", command=plot_best_batsmen, bg="#34495E", fg="white")
b5.pack(side = LEFT)

mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM