How to change labels and radiobuttons after a button clicked? - python

I have programmed a script which takes random four elements from a table and question to the user using tkinter, random and sqlite3. Currently, I can ask a question. Implement four choices with radiobuttons. I can also test if the answer is correct or not and show the result to the user via toplevel().
Problem is, how can I refresh the question after the continue button clicked?
My whole code is below. I have tried refreshing the random numbers and labels under continue_asking or another def called from continue_asking. But it doesn't work at all.
from tkinter import *
from sqlite3 import *
from random import *
class Question(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.prepare_question()
def prepare_question(self):
self.tumu = {0:['ask1','answer1'], # instead of SQL query
1:['ask2','answer2'],
2:['ask3','answer3'],
3:['ask4','answer4']}
self.create_widgets()
def create_widgets(self):
self.choiceFrame = Frame(self)
self.choiceFrame.grid(row=2, column=0)
self.choiceNum = IntVar()
for i in range(4):
Radiobutton(self.choiceFrame, text=self.tumu[i][1], variable=self.choiceNum, value=i) \
.grid(row=2, column=i, padx=5, pady=5)
self.q_num = randrange(4)
self.q_word = self.tumu[self.q_num][0]
lbl_question = Label(self, text="Which one is the meaning of the word: " + self.q_word, font="Courier 12")
lbl_question.grid(row=0, column=0, columnspan=4, padx=5, pady=5, sticky=W)
txt_question = Text(self, height=1, font="Courier 12", pady=2)
txt_question.tag_configure("myStyle", font="Courier 12 bold")
txt_question.insert("end", "Please choose the answer and ")
txt_question.insert("end", "click okay to see the results.", "myStyle")
txt_question.configure(state="disabled")
txt_question.grid(row=1, column=0, columnspan=4, padx=5, sticky=W)
btn_okay = Button(self, text="Okay", font="12", command=self.a_control)
btn_okay.grid(row=3, column=0, columnspan=2)
def a_control(self):
self.choosenWord = self.q_num
self.frm_answer = Toplevel()
self.frm_answer.title("Result")
self.selectedWord = self.choiceNum.get()
txt_result = Text(self.frm_answer, height=4, width = 40)
if self.choosenWord == self.selectedWord:
txt_result.insert("end", "Congrats! Your answer is correct.\n")
else:
txt_result.insert("end","Your answer is not correct.\n")
txt_result.insert("end", "Correct answer is " + self.tumu[self.q_num][1] + '\n')
txt_result.insert("end", "Please click Continue to continue.\n")
txt_result.insert("end", "Click cancel to quit.")
txt_result.grid(row=0, column=0, columnspan=2, padx = 5, pady=5)
txt_result.configure(state="disabled")
btn_continue = Button(self.frm_answer, text="Continue", command=lambda: self.continue_asking(self.frm_answer))
btn_continue.grid(row=1, column=0, padx=5, pady=5, sticky = W)
btn_quit = Button(self.frm_answer, text="Cancel", command=self.end_asking)
btn_quit.grid(row=1, column=1, padx=5, pady=5, sticky = W)
def continue_asking(self,frm_answer):
frm_answer.destroy()
def end_asking(self):
root.destroy()
root = Tk()
app = Question(root)
root.mainloop()
I have tried adding prepare_question to continue_asking. It keeps asking questions but widgets are not changing. They are just overlapping.

EDIT
So let's restart from scratch, i was totally wrong because no widget was removed and they stacked in the main Frame children list.
You still don't need to write so much code, mostly move some parts.
First, to be able to update the widgets and prepare the new question peacefully, move
self.create_widgets() in the constructor and put the random index self.q_num and self.q_word inside prepare_question, since it belongs to the logic of the question creation.
In create_widgets() you only need to keep some control on the label question, so we add self.lbl_question...
Finally, i suggest to create a new function update_widgets(), but you can put the logic inside continue_asking().
In this function, call prepare_question to update the next question (sql query and random stuff). Since we move the random index, everything is ready to update each widget:
text of the question label
text of radiobuttons. I'm not so proud of the loop to change those, but that'll do the trick. (we keep the values created for the indexes to match the new ones, i'm not very sure about this logic with SQL queries, i follow your first implementation with text=self.tumu[i][1])
If someone can tell how to get the radiobutton value more easily, i'm interested
Here is the whole code:
from tkinter import *
from sqlite3 import *
from random import *
class Question(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.prepare_question()
self.create_widgets()
def prepare_question(self):
self.tumu = {0:['ask1','answer1'], # instead of SQL query
1:['ask2','answer2'],
2:['ask3','answer3'],
3:['ask4','answer4']}
self.q_num = randrange(4)
self.q_word = self.tumu[self.q_num][0]
def create_widgets(self):
self.choiceFrame = Frame(self)
self.choiceFrame.grid(row=2, column=0)
self.choiceNum = IntVar()
for i in range(4):
Radiobutton(self.choiceFrame, text=self.tumu[i][1], variable=self.choiceNum, value=i) \
.grid(row=2, column=i, padx=5, pady=5)
self.lbl_question = Label(self, text="Which one is the meaning of the word: " + self.q_word, font="Courier 12")
self.lbl_question.grid(row=0, column=0, columnspan=4, padx=5, pady=5, sticky=W)
txt_question = Text(self, height=1, font="Courier 12", pady=2)
txt_question.tag_configure("myStyle", font="Courier 12 bold")
txt_question.insert("end", "Please choose the answer and ")
txt_question.insert("end", "click okay to see the results.", "myStyle")
txt_question.configure(state="disabled")
txt_question.grid(row=1, column=0, columnspan=4, padx=5, sticky=W)
btn_okay = Button(self, text="Okay", font="12", command=self.a_control)
btn_okay.grid(row=3, column=0, columnspan=2)
def a_control(self):
self.choosenWord = self.q_num
self.frm_answer = Toplevel()
self.frm_answer.title("Result")
self.selectedWord = self.choiceNum.get()
txt_result = Text(self.frm_answer, height=4, width = 40)
if self.choosenWord == self.selectedWord:
txt_result.insert("end", "Congrats! Your answer is correct.\n")
else:
txt_result.insert("end","Your answer is not correct.\n")
txt_result.insert("end", "Correct answer is " + self.tumu[self.q_num][1] + '\n')
txt_result.insert("end", "Please click Continue to continue.\n")
txt_result.insert("end", "Click cancel to quit.")
txt_result.grid(row=0, column=0, columnspan=2, padx = 5, pady=5)
txt_result.configure(state="disabled")
btn_continue = Button(self.frm_answer, text="Continue", command=self.continue_asking)
btn_continue.grid(row=1, column=0, padx=5, pady=5, sticky = W)
btn_quit = Button(self.frm_answer, text="Cancel", command=self.end_asking)
btn_quit.grid(row=1, column=1, padx=5, pady=5, sticky = W)
def continue_asking(self):
self.frm_answer.destroy()
self.update_widgets()
def update_widgets(self):
self.prepare_question()
# change question text
self.lbl_question.configure(text = "Which one is the meaning of the word: " + self.q_word)
# change Radiobutton
for child in self.choiceFrame.children.values():
index = child.config()['value'][4]
child.configure(text = self.tumu[index][1])
if index == 0: # reset the focus
child.select()
def end_asking(self):
root.destroy()
root = Tk()
app = Question(root)
root.mainloop()
First crap post: (the not to do part)
You don't need to change so much code to fix the present issue, have you already tried the following ?
def continue_asking(self,frm_answer):
frm_answer.destroy()
self.prepare_question()
I won't review the whole code, there is another place for that, but you can also avoid the lambda when you call continue_asking(), since you store the frame in self.frm_answer
btn_continue = Button(self.frm_answer, text="Continue", command=self.continue_asking)
# [...]
def continue_asking(self):
self.frm_answer.destroy()
self.prepare_question()

Related

Tkinter - How to pass a variable using modules?

I need to take a value from user and then pass this value into function to get a string with this values. My code in first file looks like below (of course it is simplified version):
import tkinter as tk
from tkinter import ttk
import myfunction # this is my module that has another function
class Interface(ttk.Frame):
def __init__(self, container):
super().__init__(container)
self.user_price_minimum = tk.StringVar()
minimum_price = ttk.Label(self, text="Minimum price is: ")
minimum_price.grid(row=0, column=0, padx=5, pady=5)
minimum_price_entry = ttk.Entry(self, width=15, textvariable = self.user_price_minimum)
minimum_price_entry.grid(row=0, column=1)
minimum_price_entry.focus()
#############
button = ttk.Button(self, text="Use price")
button.grid(column=0, rows=2, columnspan=2, padx=5, pady=5)
root = tk.Tk()
root.geometry("450x250")
root.title("Looking for a flat")
root.columnconfigure(0, weight=1)
frame = Interface(root)
frame.pack()
root.mainloop()
My another python file that calls myfunction.py should be able to take this minimum_price from user and add this into string. Code looks like below:
def minimum_price(self):
price_min = self.user_price_minimum.get()
price_min = int(price_min)
print(f'Minimum price is: {price_min}')
So I am not sure how I could use minimum_price values from user into this function.
The simplest is to do this:
button = ttk.Button(self, text="Use price", command=lambda: myfunction.minimum_price(self))
However you could also define it as a method in the class itself:
class Interface(ttk.Frame):
def __init__(self, container):
super().__init__(container)
self.user_price_minimum = tk.StringVar()
minimum_price = ttk.Label(self, text="Minimum price is: ")
minimum_price.grid(row=0, column=0, padx=5, pady=5)
minimum_price_entry = ttk.Entry(self, width=15, textvariable = self.user_price_minimum)
minimum_price_entry.grid(row=0, column=1)
minimum_price_entry.focus()
#############
button = ttk.Button(self, text="Use price", command=self.print_price)
button.grid(column=0, rows=2, columnspan=2, padx=5, pady=5)
def print_price(self):
price = self.user_price_minimum.get()
print(f'Minimum price: {price}')
My personal preference (when using another file in such a case like this one (tho I would probably prefer to define this as above)) would be if:
# in the other file
def minimum_price(value):
print(f'Minimum price: {value}')
# inside the class
button = ttk.Button(self, text="Use price", command=lambda: myfunction.minimum_price(self.user_price_minimum.get()))
Also in this case you don't necessarily need the StringVar, you could also simply get the value by using:
# assignment
self.minimum_price_entry = ttk.Entry(self, width=15)
# get value (probably in some function call, basically the same way as with the `StringVar` except less code)
self.minimum_price_entry.get()

Retrieve input from Entry widget stored as an instance variable and use it outside of the class

I have difficulties trying to get the input from Entry widget stored as a instance variable, so I can use it as input outside this class:
class CreateGUI:
def __init__(self, master):
self.master = master
self.master.geometry("275x325")
self.master.columnconfigure(0, weight=1)
self.master.columnconfigure(1, weight=2)
self.checkbutton_var1 = IntVar()
self.checkbutton_var2 = IntVar()
self.path = ''
self.type = []
def add_labels(self):
Label(self.master, text="Provide path to file:").grid(column=0, row=0, padx=10, pady=10, sticky="N")
def add_entries(self):
user_input = Entry(self.master)
user_input.grid(column=0, row=1, padx=5, pady=5, ipadx=60)
return user_input
def add_buttons(self, user_input):
checkbutton1 = Checkbutton(self.master, text="test1", variable=self.checkbutton_var1, onvalue=1,offvalue=0,height=2,width=10)
checkbutton1.grid(column=1, row=0)
checkbutton2 = Checkbutton(self.master, text="test2", variable=self.checkbutton_var2, onvalue=1, offvalue=0,height=2, width=10)
checkbutton2.grid(column=1, row=1)
button = Button(self.master, text="push", bg="pink", bd=100, fg="white",
command=lambda: self.retrieve_input(user_input.get(), self.checkbutton_var1.get(), self.checkbutton_var2.get()))
button.grid(column=0, row=3, padx=20, pady=20, sticky="NEWS")
def retrieve_input(self, p, *args):
self.path = p
#print(self.path)
for el in args:
self.type.append(el)
#print(self.type)
def main():
tk = Tk()
app = CreateGUI(tk)
app.add_labels()
user_input = app.add_entries()
app.add_buttons(user_input)
print(app.type)
print(app.path)
tk.mainloop()
When I start the program, write the input and press the button, it does not print anything. There are empty brackets printed the moment the program is initiated. The prints inside the retrieve_input are printing exactly what I need, but I need this inputs outside of the class, because they will be an input to another class.
I tried everything related to this problem, but it is not working and I would really appriciate any kind of help. Thanks!
You are getting the input for the Entry widget right before anyone can have a chance to type in it. As a result, user_input.get() will return an empty string. One thing you can do is make some sort of trigger for calling add_buttons() that the user activates when they are done filling out user_input. Further tweaking after that should make it work.
Please tell me if you have any more trouble.

converting python hangman to GUI

I am working with our project on creating guessing word. but I am having a problem regarding with loops and letters that should be added on the labelGuessResult. please help me to resolve my codes and help me to understand what's the problem to my codes. the result I would like to get are the correct guessed letters are showing in labelGuessResult and everytime I enter a correct guess it will add like this s _ren.
from tkinter import *
import tkinter.messagebox
from random import choice
randomWords = choice(["yeti", "siren", "lich"])
lives = 7
guessedWord = []
guessedWrong = []
#defining the main class
class window(Frame):
#defining main window initialization
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.init_window()
#defining main frame
def init_window(self):
self.master.title("H A N G M A N")
self.master.resizable(False, False)
self.pack(fill=BOTH, expand=1)
self.label1 = Label(self, text="Guessed the %s letter word: " % (len(randomWords)))
self.label1.grid(row=1, column=1, ipadx=5, ipady=5, sticky=W)
'''DISPLAY WORD'''
self.labelGuessResult = Label(self, text=len(randomWords)* " _")
self.labelGuessResult.grid(row=1, column=2)
'''GUESS INPUT'''
self.guessEnt = Entry(self)
self.guessEnt.grid(row=1, column=3)
guess = self.guessEnt.get()
self.label2 = Label(self, text="Message: ")
self.label2.grid(row=2, column=1, ipadx=5, ipady=5, sticky=W)
self.labelMessage = Label(self, text=guessedWord + guessedWrong)
self.labelMessage.grid(row=2, column=2)
self.label3 = Label(self, text="Guessed Letters: ")
self.label3.grid(row=3, column=1, ipadx=5, ipady=5, sticky=W)
self.lblGuessed = Label(self, text=guessedWord)
self.lblGuessed.grid(row=3, column=2)
self.label4 = Label(self, text="Lives left: ")
self.label4.grid(row=4, column=1, ipadx=5, ipady=5, sticky=W)
self.lblLives = Label(self, text=lives)
self.lblLives.grid(row=4, column=2)
def checkWord():
while True:
out = ""
for letter in randomWords:
if letter in guessedWord:
self.labelGuessResult.config(text=out+letter)
else:
self.labelGuessResult.config(text=out+" _")
if out == randomWords:
self.labelMessage.config("You have guesed the ", randomWords)
break
if guess in guessedWord:
self.labelMessage.config(text="already guessed that!")
elif guess in randomWords:
self.labelMessage.config(text="correct!")
guessedWord.append(guess)
else:
self.labelMessage.config(text="Wrong!")
guessedWrong.append(guess)
print()
'''BUTTON GUESS'''
self.submitBTN = Button(self, text="Guess", command=checkWord)
self.submitBTN.grid(row=1,column=4)
frames = Tk() #creates the frame
frames.geometry("500x450") #sets frame size
app = window(frames) #calls and runs the frame within the class
frames.mainloop() #runs the frame continuously
Well, one major problem is the checkWord() function. The first time you call this function it starts a loop that I have difficulty in understanding and which doesn't seem to end.
This means that once you call checkWord() you'll not be able to input more letters to the entry.
My suggestion is for you to first make a flowchart of the guessing and checking procedure and then implement it bit by bit while checking that you get the correct return. To begin with it may be simpler to skip the GUI because it just adds complexity until you get it to work.

How to Get Iterations to Update with addition to list

So I've been struggling with an issue for a week or so, been googling around trying to find different solutions, etc and getting nowhere. I was advised to put functioning code on here so I've cut it down some while still showing the issue.
I want to have a main page listing a set of goals, then if you click on the "Goal Entry" button up top a new window opens where you can input additional goals. Then you type in your desired additions, hit enter, and it adds it to the list on the main page.
I've accomplished all of the above EXCEPT, after you add the goals (and I have the list printing before and after so I know they're being added) and the entry window closes, the list of labels (created by an iteration) hasn't updated accordingly.
How do I get the list on the main page to automatically update when a new item is added to the list?
from tkinter import *
pg = ["goal1","goal2"]
pgtotal=1
psum=len(pg)
class yeargoals():
global pg, hg, fg, rg, rgtotal
def __init__(self,master):
self.master = master
master.title("This Year's Goals")
self.buttonframe = Frame(root)
self.buttonframe.pack(side=TOP, padx = 150, fill=BOTH)
self.home = Button(self.buttonframe, text="Home Page")
self.home.grid(row=1, column=1, padx=10)
self.enter = Button(self.buttonframe, text="Goal Entry", command=self.winenter)
self.enter.grid(row=1, column=2, padx=10)
self.finalize = Button(self.buttonframe, text="Finalize for Year")
self.finalize.grid(row=1, column=3, padx=10)
self.dashboard = Button(self.buttonframe, text="Goal Dashboard")
self.dashboard.grid(row=1,column=4, padx=10)
self.goalframe = Frame(root)
self.goalframe.pack(side=TOP, padx=150, pady=50, fill=BOTH, expand = True)
#Makes the label Fram I want the Checkboxes to go in
self.LabelFramep= LabelFrame(self.goalframe,text="Professional Goals")
self.LabelFramep.pack(side=LEFT, padx=10, anchor = N, fill=BOTH, expand = True)
#Makes the from the list above
for goal in pg:
l = Checkbutton(self.LabelFramep, text=goal, variable=Variable())
l.config(font=("Courier",12))
l.grid(sticky=W)
self.ptotal=Label(self.LabelFramep,text="Progress so far: "+str(pgtotal)+"/"+str(psum))
self.ptotal.config(font=("Courier",12))
self.ptotal.grid(sticky=W)
self.pper=Label(self.LabelFramep, text=str(round((pgtotal/psum)*100))+"% Complete")
self.pper.config(font=("Courier",12))
self.pper.grid(sticky=W)
def winenter(self):
global pg
self.winenter = Toplevel(root)
options = ["Professional", "Health", "Financial", "Reward Items"]
variable = StringVar(self.winenter)
variable.set(options[0])
#Title of entry section
t1 = Label(self.winenter, text="New Goal Entry")
t1.grid(row=0, column=1, columnspan=2)
#dropdown menu
d = OptionMenu(self.winenter, variable, *options)
d.grid(row=1, column=2)
#entry fields
e1 = Entry(self.winenter)
e1.grid(row=2, column=2, padx = 10, pady=5)
e2 = Entry(self.winenter)
e2.grid(row=3, column=2, padx=10, pady=5)
e3 = Entry(self.winenter)
e3.grid(row=4, column=2, padx=10, pady=5)
e4 = Entry(self.winenter)
e4.grid(row=5, column=2, padx=10, pady=5)
e5 = Entry(self.winenter)
e5.grid(row=6, column=2, padx=10, pady=5)
#Label for entry fields
l1 = Label(self.winenter, text="Goal Number 1")
l1.grid(row=2, column=1)
l2 = Label(self.winenter, text="Goal Number 2")
l2.grid(row=3, column=1)
l3 = Label(self.winenter, text="Goal Number 3")
l3.grid(row=4, column=1)
l4 = Label(self.winenter, text="Goal Number 4")
l4.grid(row=5, column=1)
l5 = Label(self.winenter, text="Goal Number 5")
l5.grid(row=6, column=1)
def enter():
global pg, main
print (pg)
if variable.get() == "Professional":
pg.append(e1.get())
self.winenter.destroy()
print (pg)
#Goal entry execute button
b = Button(self.winenter, text="Enter Goals", command=enter)
b.grid(row=7, column = 1)
root = Tk()
Window = yeargoals(root)
root.mainloop()
In your callback function to button "Enter Goals", you have done nothing to update your main window. Maybe you think the main window will magically keep updated with the variable pg, no, you need to do all those updates manually in your callback function.
For example, change your callback enter() to:
def enter():
global pg, main
print (pg)
if variable.get() == "Professional":
pg.append(e1.get())
l = Checkbutton(self.LabelFramep, text=pg[-1], variable=Variable())
l.config(font=("Courier",12))
l.grid(sticky=W)
self.winenter.destroy()
print (pg)
You can find the main window is updated after you click "Enter Goals".

Python3.6 : Trying to avoid using a global for my swap function with tkinter

I have only been programming 3 months so any advice on improvement to my code is appreciated even if it inst related to my specific question.
Its a simple small project with tkinter. Two fields to enter your first and last name then you hit the swap button and it will swap what ever you put in the name fields.
Problem is I dont want to use globals and I cant seem to figure it out I know its probably something easy and I did spend time trying to figure it out.
If you have any improvements to the code let me know.
from tkinter import *
### I dont Want Globals but cant figure out another method for doing this
### Hope some one can help me with this part
evar = ""
evar1 = ""
def mainWindow():
root = Tk()
root.title("Swap Names")
root.geometry("400x150+100+250")
return root
def createVar():
global evar
global evar1
evar = StringVar()
evar1 = StringVar()
def firstNameFrame(root):
frame1 = Frame(root)
frame1.pack(side=TOP, padx=2, pady=2)
label = Label(frame1, text="First Name:")
label.pack(side=LEFT, padx=2, pady=2)
entry = Entry(frame1, textvariable = evar)
entry.pack(side=LEFT, pady = 2)
def lastNameFrame(root):
frame2 = Frame(root)
frame2.pack(side=TOP, padx=2, pady=2)
label = Label(frame2, text="Last Name:")
label.pack(side=LEFT, padx=1, pady=1)
entry = Entry(frame2, textvariable = evar1)
entry.pack(side=LEFT, pady = 5)
def swapFrame(root):
frame3 = Frame(root)
frame3.pack(side=TOP, padx=10, pady = 10)
swapButton = Button(frame3, text="Swap",command = swap)
swapButton.pack(side=LEFT, padx =5, pady=5)
### I would like to some how use swap with out using a global
def swap():
b=evar.get()
evar.set(evar1.get())
evar1.set(b)
def main():
root = mainWindow()
createVar()
firstNameFrame(root)
lastNameFrame(root)
swapFrame(root)
root.mainloop()
main()
One of the solutions can be wrapping all the code related to the initialization and working with Tk in a separate class, so instead of global variables, we will use the class instance variables:
from tkinter import *
class Gui(object):
def __init__(self):
self.root = Gui._init_main_window()
self.first_name_var = StringVar()
self.last_name_var = StringVar()
self._init_first_name_frame()
self._init_last_name_frame()
self._init_swap_frame()
#staticmethod
def _init_main_window():
root = Tk()
root.title("Swap Names")
root.geometry("400x150+100+250")
return root
def _init_first_name_frame(self):
frame1 = Frame(self.root)
frame1.pack(side=TOP, padx=2, pady=2)
label = Label(frame1, text="First Name:")
label.pack(side=LEFT, padx=2, pady=2)
entry = Entry(frame1, textvariable=self.first_name_var)
entry.pack(side=LEFT, pady=2)
def _init_last_name_frame(self):
frame2 = Frame(self.root)
frame2.pack(side=TOP, padx=2, pady=2)
label = Label(frame2, text="Last Name:")
label.pack(side=LEFT, padx=1, pady=1)
entry = Entry(frame2, textvariable=self.last_name_var)
entry.pack(side=LEFT, pady=5)
def _init_swap_frame(self):
frame3 = Frame(self.root)
frame3.pack(side=TOP, padx=10, pady=10)
swap_button = Button(frame3, text="Swap", command=self._swap)
swap_button.pack(side=LEFT, padx=5, pady=5)
def _swap(self):
tmp = self.first_name_var.get()
self.first_name_var.set(self.last_name_var.get())
self.last_name_var.set(tmp)
def mainloop(self):
return self.root.mainloop()
def main():
gui = Gui()
gui.mainloop()
if __name__ == '__main__':
main()
A small comment to the code above: adding a prefix __ to variables or methods allows you to hide access to them directly by name outside the class using the name mangling.
UPD: According to #Coal comment, changed the double underscore prefixes to single underscore, as there is no need to use a name mangling.
This is assuming that when you say you don't want to use global, that you also mean that you don't want to use self:
from tkinter import Tk, Button, Entry
def swap(fn, ln):
# Get the contents of the two fields.
first = fn.get()
last = ln.get()
# Clear the contents of both fields.
first_name.delete(0, 'end')
last_name.delete(0, 'end')
# Set each field to the previous content of the other field.
first_name.insert(0, last)
last_name.insert(0, first)
root = Tk()
first_name = Entry(root)
last_name = Entry(root)
first_name.insert(0, "Enter first name")
last_name.insert(0, "Enter last name")
first_name.pack()
last_name.pack()
swap_button = Button(root, text="SWAP", command=lambda:swap(first_name, last_name))
swap_button.pack()
root.mainloop()

Categories

Resources