pyhton tkinter append list - python

I have written a bit of code, but my problem is it puts <tkinter.Entry object .!entry> every time I press the "add words" button. Any suggestions on how to fix this problem?
import tkinter as tk
balls = tk.Tk()
CensoredList=[]
window1 = tk.Canvas(balls, width = 400, height = 300)
window1.pack()
title = tk.Label(balls, text="Bad Word Blocker")
title.config(font=("Bahnschrift", 14))
window1.create_window(200, 25, window=title)
subtitle = tk.Label(balls, text="Enter a word or phrase you
would like blocked:")
subtitle.config(font=("Bahnschrift", 10))
window1.create_window(200, 100, window=subtitle)
entry = tk.Entry(balls)
window1.create_window(200, 140, window=entry)
def fobblejibbits():
CensoredList.append(entry)
def heebyjeeby():
print(CensoredList)
pressme = tk.Button(balls, text ="add word to list", command =
fobblejibbits)
pressme.pack()
pressme2 = tk.Button(balls, text ="are you done adding words",
command = heebyjeeby)
pressme2.pack()
balls.mainloop()

You would need to add in a variable to associate as text with the entry field. Following is a code snippet that does that.
import tkinter as tk
balls = tk.Tk()
CensoredList=[]
name_var=tk.StringVar() # Add this
window1 = tk.Canvas(balls, width = 400, height = 300)
window1.pack()
title = tk.Label(balls, text="Bad Word Blocker")
title.config(font=("Bahnschrift", 14))
window1.create_window(200, 25, window=title)
subtitle = tk.Label(balls, text="Enter a word or phrase you would like blocked:")
subtitle.config(font=("Bahnschrift", 10))
window1.create_window(200, 100, window=subtitle)
entry = tk.Entry(balls, textvariable = name_var) # Note the use of the string variable here
window1.create_window(200, 140, window=entry)
def fobblejibbits():
name=name_var.get() # Add this
CensoredList.append(name)
name_var.set("") # Clear the field
def heebyjeeby():
print(CensoredList)
pressme = tk.Button(balls, text ="add word to list", command = fobblejibbits)
pressme.pack()
pressme2 = tk.Button(balls, text ="are you done adding words", command = heebyjeeby)
pressme2.pack()
balls.mainloop()
The field added is the string variable "name_var".
When I tested out the program, I pumped out a list to the terminal.
#Una:~/Python_Programs/Censored$ python3 Censored.py
['Hello', 'Goodbye']
Give that a try.

Related

Tkinter - My button wont call the command and it shows no error

I have created a back button on my canvas in tkinter, I am hoping it will either bring it back to a different canvas, or it will call the command.
It is not calling the command I put and it is not showing an error.
This is the function:
def instructions():
print ("TEST")
#root4.destroy()
root5 = Tk()#creates pop up box
game2 = Canvas(root5, width = 800, height = 600, bg = "slate gray")
game2.pack()
welcomeText2 = game2.create_text(150, 50, text = ("Welcome Back!"), font = ('Calibri', '16'))
instructions2 = game2.create_text(175, 115, text = "Instructions:", font = ('Calibri', '14'))
Instructions2 = game2.create_text(190, 325, text = "To play the game Who Did It?\n all you need to do is read the\n details of the story and think\n about who you think did the\n crime. There will be 3 options\n and when you have your guess\n select the person you think did\n it. Once you hit confirm the answer\n will be displayed! Hit the back\n button at any time to read the\n instructions again, or choose a\n new story. However, all progress\n will be lost if you hit the button.\n To start the game select the story\n and hit continue on the left!", font = ('Calibri', '10'))
rectangle2 = game2.create_rectangle(30, 140, 350, 510, width = 2)
detective2 = PhotoImage(file = "detective.gif")
Detective2 = game2.create_image(600, 100, image = detective2)
storyChoiceText2 = game2.create_text(550, 250, text = "Please Select Story", font = ('Calibri', '14'))
storyChoice2 = StringVar(root5)
storyChoice2.set("Select")
option_menu2 = OptionMenu(root5, storyChoice2, "Story 1 - Easy", "Story 2 - Medium", "Story 3 - Hard")
option_menu2.pack()
storyChoiceWindow2 = game2.create_window(550, 300, window = option_menu2)
continueButton2 = Button (root5, text = "Continue", command = choice)
coninuteGameButton2 = game2.create_window (700, 550, window = continueButton2)
and this is the button code:
backButton = Button(root2, text = "Back", command = instructions)
backButtonGame = Story1.create_window(750, 550, window = backButton)
Any solutions?
You have to make a button-function for your button and define its properties outside that specific function, but on another note this code is hiatus and should not be written with more that one root, try using TopLevel instead and then seperately define your button again.

reading and playing a word in the message window

I have a problem with the code and an error message appears in word -> word = "" word = str (Entry.get (input_text)) which obviously refers to printing full text which does not work the way I want it when I want it to work in a non-root window window but reading window.
This is the codes :
from tkinter import *
import sys
import tkinter as tk
from tkinter import messagebox
#---------
root = Tk()
root.title("Window")
#----------
#toiminnot root ikkunassa
functions = Label(root, text = "Select an action!")
functions.place(x = 70, y= 10)
#lue toimonto koodi alkaa
def read():
reading_window = Tk()
reading_window.title("Read function")
frame = Frame(reading_window)
frame.pack()
read_the_text = Label(reading_window, text = "Enter text in the box!")
read_the_text.place(x = 70, y = 10)
word = ""
word = str(Entry.get(input_text))
#frame johon kirjoitetaan
input_text = Entry(reading_window)
input_text.place(x=55, y=30)
#lueikkuna koko ja sijoitus
reading_window.geometry("300x300+100+100")
#lue sana painike joka tuo viestin
print_button = tk.Button(reading_window, text = 'Show typed text', height = 1, width = 15) #, command = print1)
print_button.place(x=80, y=60)
text_a_tip = Label(reading_window, text ="The typed text is displayed in\nthe message window!")
text_a_tip.place(x = 50, y = 90)
def print1():
tk.messagebox.showinfo('Kirjoitetun tekstin tulostus viestiikkunaan', (Entry.get(input_text)))
def close():
reading_window.destroy()
read_close_button = tk.Button(reading_window, text = 'Close the reading function', height = 1, width = 20, command = close)
read_close_button.place(x = 60, y = 270)
read.mainloop()
#lue toiminto koodi loppuu
read_function = tk.Button(root, text='Read function', height = 1, width = 15, command = read)
read_function.place(x = 55,y = 35)
#ohjleman lopettamisen koodi alkaa
def quit_prog():
MsgBox = tk.messagebox.askquestion('Quit program', ' Are you sure you want to close the program?',icon = 'warning')
if MsgBox == 'yes':
root.destroy()
sys.exit(0)
else:
tk.messagebox.showinfo('Back','Now you are back!')
quit_programbutton = tk.Button(root, text='Close program', height = 1, width = 15, command = quit_prog)
quit_programbutton.place(x=50, y=220)
#ohjelman lopettamisen koodi loppuu tähän
#----------
#----------
root.geometry("250x250+20+60") #"450x450=leveysxkorkeus"+"20+40=vasenreuna+yläreuna"
root.mainloop()
source
I don't really see what is "word" variable for, but I assume that You need it. You can't use variable defined under line in which you use it.
word = ""
word = str(Entry.get(input_text)) # input_text is defined below, interpreter doesn't know what is it "input_text" yet.
input_text = Entry(reading_window)
input_text.place(x=55, y=30)
It should be rather.
input_text = Entry(reading_window)
input_text.place(x=55, y=30)
word = ""
word = str(Entry.get(input_text)) # now there is no error
It doesn't solve your problem, because I see that in function print1 you use again imput_text but it's defined in different function so it won't work.
def print1():
# input_text is local variable in read function.
tk.messagebox.showinfo('Kirjoitetun tekstin tulostus viestiikkunaan', (Entry.get(input_text)))
To solve your problem you can pass input_text as argument of print1, like in this working example.
def read():
reading_window = Tk()
reading_window.title("Read function")
frame = Frame(reading_window)
frame.pack()
read_the_text = Label(reading_window, text = "Enter text in the box!")
read_the_text.place(x = 70, y = 10)
input_text = Entry(reading_window)
input_text.place(x=55, y=30)
word = ""
word = str(Entry.get(input_text))
reading_window.geometry("300x300+100+100")
# pass input_text to print1
print_button = tk.Button(reading_window, text = 'Show typed text', height = 1, width = 15, command = lambda: print1(input_text))
print_button.place(x=80, y=60)
text_a_tip = Label(reading_window, text ="The typed text is displayed in\nthe message window!")
text_a_tip.place(x = 50, y = 90)
def print1(input_text):
# print1 takes now one argument and has reference to input_text
tk.messagebox.showinfo('Kirjoitetun tekstin tulostus viestiikkunaan', (Entry.get(input_text)))
def close():
reading_window.destroy()
read_close_button = tk.Button(reading_window, text = 'Close the reading function', height = 1, width = 20, command = close)
read_close_button.place(x = 60, y = 270)
read.mainloop()
Consider also using different geometry manager than place, it is even written in effbot doc:
It is usually not a good idea to use place for ordinary window and dialog layouts; its simply to much work to get things working as they should. Use the pack or grid managers for such purposes.
Place Geometry Manager

Issue with adding images to button in tkinter application

I am helping with a small project where we want to add and take items away from a store. The code is below:
from tkinter import *
import tkinter
####################
# Variables
eggs = 0
milk = 0
butter = 0
lemon = 0
guiSize = "800x1280"
def newItemGUI():
main.withdraw()
def addEgg():
global eggs
eggs += 1
updateLabels()
def menu():
global eggs
update(eggs)
itemWindow.destroy()
main.deiconify()
def updateLabels():
eggLabel = Label(itemWindow, text = eggs)
eggLabel.grid(row = 3,column = 0)
itemWindow = Toplevel()
itemWindow.geometry(guiSize)
itemWindow.title("Add a new item")
itemWindow.configure(background = "#a1dbcd")
heading = Label(itemWindow, text="Add new items", font=("Arial",20),background = "#a1dbcd")
heading.grid(row=0, columnspan = 3)
egg = PhotoImage(file ="images/egg.gif")
eggButton = Button(itemWindow, image = egg, command = addEgg)
eggButton.grid(row = 2, column = 0,padx = 10, pady = 10)
eggLabel = Label(itemWindow, text = eggs).grid(row = 3,column = 0)
back = Button(itemWindow, text = "Main Menu", command = menu, width = 15)
back.grid(row = 4, column = 0, padx = 20, pady = 20)
def update(eggs):
items.delete("1.0",END)
items.insert(END,"Eggs \t:")
items.insert(END,eggs)
items.insert(END,"\n")
main=tkinter.Tk()
main.geometry(guiSize)
bgColour = "#DDA0DD"
main.configure(background = bgColour)
button1 = Button(main, text="Input new products", width = 20, height = 5, command = newItemGUI)
button1.grid(column = 1, row =2, padx = 20, pady = 20)
label2 = Label(main,text = "Items in the fridge :", font =("Arial,20"), background = bgColour)
label2.grid(row=4, columnspan = 2)
items = Text(main, width = 60, height = 10)
items.insert(END,"Eggs \t:")
items.insert(END,eggs)
items.insert(END,"\n")
items.grid(row=5, columnspan = 4)
main.mainloop()
When you click on the input new products button, this takes you to a new screen. On the screen should be a photo of an egg with a count underneath. For some reason the image of the egg is not showing and the button will not click.
If I change the eggButton from an image to:
eggButton = Button(itemWindow, text = "egg", command = addEgg)
this seems to allow me to click and the variable and it increases. Any idea as to what/where we have gone wrong? I know the path is correct as I can get the button to display a picture of an egg in a Label.
The problem is because the PhotoImage is being stored in a variable named egg which is local to the newItemGUI() function, so it (and associated image object) are being deleted when the function returns. This is a fairly common problem, so your question is likely a duplicate of another (and may get closed).
This PhotoImage documentation mentions avoiding this potential issue the way shown below in the Note near the end.
Regardless, to prevent that from happening, you can store the value somewhere else such as in an attribute of the Toplevel window. I would also recommend changing its name to something more descriptive like egg_image.
Here are changes to your code showing what how it could be done:
itemWindow.egg_image = PhotoImage(file="images/egg.gif")
eggButton = Button(itemWindow, image=itemWindow.egg_image, command = addEgg)

overlapping statuses using tkinter module

I am trying to work on GUI using tkinter module. I created label with random greetings generator. However,they are overlapping with previous generated labels.This is the code:
import tkinter
import random
window = tkinter.Tk()
# to rename the title of the window
window.title("GUI")
window.geometry("500x500")
#defining Functions
def search_greetings():
phrases = ["Hallo ", "Hoi ", "Greetings "]
name = str(entry1.get())
text = ".Please enter your search term below."
return phrases[random.randint(0, 2)] + name + text
def search_display():
greeting = search_greetings()
# This creates the text field
greeting_display = tkinter.Label(window,text = search_greetings())
greeting_display.grid(row=6,column=1)
search_box = tkinter.Entry()
search_box.grid(row=7)
# pack is used to show the object in the window
label = tkinter.Label(window, text = "Hello World! Welcome to my app")
label.grid(row = 0)
# creating 2 text labels and input labels
tkinter.Label(window, text = "Username").grid(row = 2) # this is placed in 1 0
# 'Entry' is used to display the input-field
entry1 = tkinter.Entry()
entry1.grid(row = 2, column = 1) # this is placed in 1 1
tkinter.Label(window, text = "Password").grid(row = 3) # this is placed in 2 0
tkinter.Entry().grid(row = 3, column = 1) # this is placed in 2 1
# 'Checkbutton' is used to create the check buttons
tkinter.Checkbutton(window, text = "Keep Me Logged In").grid(columnspan = 2) # 'columnspan' tells to take the width of 2 columns
# you can also use 'rowspan' in the similar manner
# Submit button
button = tkinter.Button(text = "Submit",command = search_display).grid(row = 5)
window.mainloop()
It is returning the labels like below:
Greetings 1234.Please enter your search term below.
G Hallo ashita.Please enter your search term below.v.
G Hallo ashita.Please enter your search term below..v.
Please check the error in the code.
Seems like you are making a new Label every time. You can edit a Label's text like so:
mylabel = tkinter.Label(root, text="First!")
mylabel["text"] = "Second!"
This will display "Second!" (after being packed). You can even change the text after the Label is packed.

Tkinter entry widget .get doesn't work

I am fairly new to python and am currently working on a school project, my aim is to create a search bar that can be used to search a data file, however I am struggling to get the search bar to work correctly. I am using the tkinter entry widget.
When I call .get(), the string in the entry widget is not printed. Here is my code...
from tkinter import *
def searchButton():
text = searched.get()
print (text)
def drawStatWindow():
global searched
statWindow = Tk()
statWindow.title("View Statistics")
statWindow.config(bg = "grey")
statWindow.geometry('800x900')
searched = StringVar()
searchBox = Entry(statWindow, textvariable = searched)
searchBox.place(x= 450, y=50, width = 200, height = 24)
enterButton = tkinter.Button(statWindow, text ="Enter", command =searchButton)
enterButton.config(height = 1, width = 4)
enterButton.place(x=652, y=50)
drawStatWindow()
When I type a string into the entry widget and press the enter button, nothing happens.
Like I say I am not very experienced and this is my first project, but after reading about the tkinter entry widgets I can't understand why this won't work.
I am using python V3.4.0
Thanks.
Your code lacks a call to mainloop(). You could try adding it to the end of the drawStatWindow() function:
statWindow.mainloop()
You might want to restructure your code into a class. This allows you to avoid using global variables and generally provides better organisation for your application:
from tkinter import *
class App:
def __init__(self, statWindow):
statWindow.title("View Statistics")
statWindow.config(bg = "grey")
statWindow.geometry('800x900')
self.searched = StringVar()
searchBox = Entry(statWindow, textvariable=self.searched)
searchBox.place(x= 450, y=50, width = 200, height = 24)
enterButton = Button(statWindow, text ="Enter", command=self.searchButton)
enterButton.config(height = 1, width = 4)
enterButton.place(x=652, y=50)
def searchButton(self):
text = self.searched.get()
print(text)
root = Tk()
app = App(root)
root.mainloop()
You have to add mainloop() because tkinter needs it to run.
If you run code in IDLE which use tkinter then IDLE runs own mainloop() and code can work but normally you have to add mainloop() at the end.
And you have to remove tkinter in tkinter.Button.
from tkinter import *
def searchButton():
text = searched.get()
print(text)
def drawStatWindow():
global searched
statWindow = Tk()
statWindow.title("View Statistics")
statWindow.config(bg="grey")
statWindow.geometry('800x900')
searched = StringVar()
searchBox = Entry(statWindow, textvariable=searched)
searchBox.place(x= 450, y=50, width=200, height=24)
# remove `tkinter` in `tkinter.Button`
enterButton = Button(statWindow, text="Enter", command=searchButton)
enterButton.config(height=1, width=4)
enterButton.place(x=652, y=50)
# add `mainloop()`
statWindow.mainloop()
drawStatWindow()
No need to use textvariable, you should use this:
searchBox = Entry(statWindow)
searchBox.focus_set()
searchBox.place(x= 450, y=50, width = 200, height = 24)
then you will be able to use searchBox.get(), that will be a string.

Categories

Resources