How to config a canvas.create_text() in function in Tkinter? [duplicate] - python

This question already has answers here:
How to reconfigure tkinter canvas items?
(2 answers)
Closed 1 year ago.
While learning Tkinter, I got a problem while creating a function for a button.
I need to config a canvas text in function. But I don't know how to do it.
canvas.create_text(700,350,font=("Arial Bold", 35),fill='white')
def clicked():
res = "THANKYOU " + txt.get()
res1.config(text=res)
I want that res1 to be that canvas.create_text()

You can make use of canvas.itemconfig/canvas.itemconfigure to change the properties of items on canvas.
minimal example:
import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root, bg="black")
canvas.pack()
text = canvas.create_text((100,50),text="Hello", fill='white')
def clicked():
res = "THANKYOU "
canvas.itemconfig(text, text=res)
tk.Button(root, text="click", command=clicked).pack()
root.mainloop()

Related

Photo not displaying in Tkinter [duplicate]

This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Closed 6 months ago.
I am trying to make a sprite sheet editor.
I have a button where you can select an image.
When I put the code in a function it doesn't work, but when it is outside a function it does work.
The BrowseComputer function is what I am having a problem with
from tkinter import *
from tkinter import filedialog
#Window specs
window = Tk()
window.title("TileSplit")
window.configure(background="white")
filepath = ""
#Searches computer and displays Image
def BrowseCompter():
filepath = filedialog.askopenfilename()
photo = PhotoImage(file = filepath)
print(filepath)
SelectedImage = Label(window, image=photo, bg="White").grid(row=0,column=0)
#Makes a variable with information about the instruction text on the screen, Sets the text background, Text color, font and location
InstructionsLabel = Label(window, text="Please select the image you would like to split:" ,bg="white" ,font= "none 12 bold")
EmptyLabel = Label(window, text="" ,bg="white" ,font= "none 12 bold")
#Makes a button
ImportImageButton = Button(window, text="Browse:", command=BrowseCompter)
#Location data
InstructionsLabel.grid(row=0, column=60, sticky=E)
ImportImageButton.grid(row=3,column=0)
EmptyLabel.grid(row=1, column=0)
#Tells python to make the window
window.mainloop()
I think you have a typo. The function shown is actually named 'BrowseCompter'.
also you might need to change your command in the button from 'BrowseCompter' to 'BrowseCompter()'

Tkinter entry widget execution [duplicate]

This question already exists:
Entry widget in tkinter
Closed 1 year ago.
So I made a simple program however it doesn't seem to work
my code is:
e = Entry(root, font = 20,borderwidth=5)
e.grid(row=1)
def capture(event):
print(e.get())
e.bind("<Key>", capture)
However the first time I enter something in the box, all I get is an empty string.
As #Art stated:
You can use "<KeyRelease>", e.bind("<Key>", lambda event: e.after(1, capture, event))" or simply Use StringVar()
from tkinter import *
root=Tk()
e = Entry(root, font = 20,borderwidth=5)
e.grid(row=1)
def capture(event):
print(e.get())
e.bind("<Key>", lambda event: e.after(1, capture, event))
root.mainloop()
Or you can use a StringVar()
from tkinter import *
root=Tk()
s=StringVar()
e = Entry(root,textvariable=s, font = 20,borderwidth=5)
e.grid(row=1)
def capture(*args):
print(s.get())
s.trace("w",capture)
root.mainloop()

How to return value from tkinter combobox [duplicate]

This question already has answers here:
Why is my Button's command executed immediately when I create the Button, and not when I click it? [duplicate]
(5 answers)
Closed 3 years ago.
I'm working on small program to work with excel data.But i cant seem to return the value from combo box so findTotal() doesn't work as intended
Excel file here: https://drive.google.com/open?id=1NYYzNvm_QlD2LbP0RLCwG8uuKf7chAC1
import tkinter as tk
from tkinter import ttk
from tkinter import *
import pandas as pd
df = pd.read_excel("some excel file")
def findTotal():
df["Total"] = (df["Oct"] + df["Nov"] + df["Dec"])*df["$ value"]
a = df.loc[(df.Country == combo.get()) & (df.incoterm == combo1.get())]
print(a.Total.sum()/len(a))
root = tk.Tk()
root.title("Data calculator")
root.configure(background="black")
root.resizable(0, 0)
canvas1 = Canvas(root, width=250, height=250, bg='lightsteelblue')
canvas1.pack()
combo = ttk.Combobox(root,
values=["USA", "Japan", "China", "Russia"])
combo1 = ttk.Combobox(root,
values=["EXW", "FOB", "DAT"])
But = Button(root, fg="red", text="Calculate", command=findTotal())
combo.current(1)
combo1.current(1)
canvas1.create_window(125, 50, window=combo)
canvas1.create_window(125, 110, window=combo1)
canvas1.create_window(125, 200, window=But)
root.mainloop()
When I run the program I get nan, actual output is somewhere around 2******
If you assign a handler to a button press you need to provide the function name - not call that function. The calling is done when the button is pressed:
But = Button(root, fg="red", text="Calculate", command=findTotal) # just the name here
Suggested as comment by Himal

Images in Tkinter [duplicate]

This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Closed 4 years ago.
How come I can't add images using this:
from tkinter import *
root = Tk()
def logo():
photo = PhotoImage(file="Logo.png")
Label(root, image=photo).grid()
logo()
root.mainloop()
But I can add images using this:
from tkinter import *
root = Tk()
photo = PhotoImage(file="Logo.png")
Label(window, image=photo).grid()
logo()
root.mainloop()
Any help?
You have to keep a reference to the image to prevent it being garbage collected. Try this:
def logo():
photo = PhotoImage(file="Logo.png")
lbl = Label(root, image=photo)
lbl.image = photo # keep a reference
lbl.grid()
You don't have to do that in your other block because you are using global variables, which are never garbage collected.
See the note on the bottom of this page.

Python tkinter limit entry input [duplicate]

This question already has an answer here:
(Python) How to limit an entry box to 2 characters max [duplicate]
(1 answer)
Closed 5 years ago.
How do I limit the input on a Entry to only 4 characters
from tkinter import *
window = Tk()
display = Entry(window)
display.grid()
You can do this by running a trace on the attribute textvariable of the entry widget. Whenever this variable is updated you will need to set the variable to it's own value up to the 4th character.
See below:
from tkinter import *
class App:
def __init__(self, root):
self.root = root
self.sv = StringVar()
self.entry = Entry(root, textvariable = self.sv)
self.entry.pack()
self.sv.trace("w", lambda name, index, mode, sv=self.sv: self.callback(self.sv))
def callback(self, sv):
self.sv.set(self.sv.get()[:4])
root = Tk()
App(root)
root.mainloop()

Categories