Home > other >  How to set the text in python tkinter
How to set the text in python tkinter

Time:10-11

from tkinter import *
from tkinter import messagebox
from PIL import ImageTk,Image
root= Tk()
root.title("Project")
root.geometry('500x600')
root.title('Choose Answer')
var = IntVar()
textt = StringVar()
print(textt.set('Clicked..........'))
def Result():
    print(textt.set('You Clicked....................'))
    if(var.get() == 1):
        print(var.get())
        print(textt)
        textt.set('You Clicked')
        resultText = Label(root, text=textt , fg='white',bg='gray', width=40)
        resultText.place(x=100,y=200)
    else:
        textt.set('You did\'t Click')
        resultText = Label(root, text=textt, fg='white',bg='grey', width=40)
        resultText.place(x=100,y=200)



checkBox = Checkbutton(root, text='Did you Study Math', variable=var, bg='grey')
checkBox.place(x=50,y=50)
button = Button(root, text='Select', fg='white', bg='grey',font='sans-serif',command=Result)
button.place(x=50,y=100)

root.mainloop()

I want to set the answer the answer using the set method without writing it in the text attribute in the Label and also I want to change the message without displaying the messages over each other I want the new message to appear and the one before it to disappear, I tried to use the set and get methods but it used to return it's default Value without using the value in the set method and I don't know why?

CodePudding user response:

This should work:

from tkinter import *
root = Tk()
root.title("Project")
root.geometry('500x600')
root.title('Choose Answer')
var = IntVar()
textt = StringVar()
resultText = Label(root, textvariable=textt , fg='white',bg='gray', width=40)
resultText.place(x=100,y=200)
def Result():
    print(var.get())
    if var.get() == 1:
        textt.set('You Clicked')
    else:
        textt.set('You didn\'t Click')

checkBox = Checkbutton(root, text='Did you Study Math', variable=var, bg='grey')
checkBox.place(x=50,y=50)
button = Button(root, text='Select', fg='white', bg='grey',font='sans-serif',command=Result)
button.place(x=50,y=100)

root.mainloop()

When you create resultText, instead of setting the text argument to textt, you need to set the textvariable argument to text. That way, the text of the variable is automatically changed when you change textt.

I removed all the lines where resultText was recreated and re-placed, and just created it once before defining Result(). Also, I removed from tkinter import messagebox, because you already import it when you call from tkinter import *. Just a note: wildcard imports are discouraged, so try to avoid using them in the future.

  • Related