I want to create a message box that confirms the intent to delete.
def delete_action(self):
s_id = self.selected_ID_entry.get()
s_name = self.seletedEntry.get()
answer = messagebox.askquestion("Delete?","Are you sure you want to delete {}".format(s_name), icon='warning')
if answer == 'yes':
#deleted function here
else:
#not deleted function here
How to highlight the "No" button instead of the "Yes" button?
You can set a default value as a keyword argument; something like this:
import tkinter as tk
from tkinter import messagebox
def quid():
messagebox.askyesno("What", "What???????????", default='no')
root = tk.Tk()
ask = tk.Button(root, text='what?', command=quid)
ask.pack()
root.mainloop()
Related
from tkinter import *
from tkinter import messagebox, simpledialog
from tkinter.messagebox import askokcancel, showinfo, WARNING
app = []
def main():
USER_INP = simpledialog.askstring(title="App Name",
prompt="Insert the name of the app:")
print(USER_INP)
answer = askokcancel(
title='DELETION',
message='Are you sure?',
icon=WARNING)
if answer:
print(answer)
messagebox.showinfo("INFO", "User pressed yes")
app.append(USER_INP)
else:
messagebox.showinfo("INFO", "User pressed cancel")
root = Tk()
myButton = Button(root, text='input', command=main)
myButton.pack()
root.mainloop()
What I want to happen here is if the user presses the input button, then the Insert the app name window pops up. If he presses cancel I want it to just stop there and do nothing. To be more exact I dont want it to go into the answer = askokcancel part.
if USER_INP is None:
return
I just used this
I want a Text label in tkinter to constantly check if its worth some value. I would like it to be in a while loop and exit it when the values match.
My code doesn't work.
while user_input != str(ans):
master = Tk()
master.title("Math")
master.geometry('400x400')
eq = generate_equation(stage=current_stage)
ans = calc(eq)
Label(master=master,text=f"score: {score}").grid(row=0,column=2,sticky=W)
Label(master=master, text=f"{q_num}: {eq}").grid(row=0,column=0 ,sticky=W)
inputtxt = tkinter.Text(master=master,height = 5, width = 20)
inputtxt.grid()
user_input =str(inputtxt.get(1.0,"end-1c"))
mainloop()
Try this:
import tkinter as tk
def check(event:tk.Event=None) -> None:
if text.get("0.0", "end").strip() == "answer":
# You can change this to something else:
text.insert("end", "\n\nCorrect")
text.config(state="disabled", bg="grey70")
root = tk.Tk()
text = tk.Text(root)
# Each time the user releases a key call `check`
text.bind("<KeyRelease>", check)
text.pack()
root.mainloop()
It binds to each KeyRelease and checks if the text in the text box is equal to "answer". If it is, it displays "Correct" and locks the text box, but you can change that to anything you like.
Please note that this is the simplest answer and doesn't account for things like your code adding things to the text box. For that you will need more sophisticated code like this.
I'm still working on the translator app, with the help of Python Dictionary. But I have this challenge: I want to be able to right click in the entry widget and paste keys as well as right click in the output widget and copy values. I'm only able to do so with keyboard shortcut; for convenience sake, I want to be able to do so with the mouse. Thanks. Below is the code:
from tkinter import *
import tkinter. messagebox
root=Tk()
root.geometry('250x250')
root.title("Meta' Translator")
root.configure(background="#35424a")
from playsound import playsound
#Entry widget object
textin = StringVar()
#press ENTER key to activate translate button
def returnPressed(event):
clk()
def clk():
entered = ent.get().lower() #get user input and convert to lowercase
output.delete(0.0,END)
if len(entered) > 0:
try:
textin = exlist[entered]
except:
textin = 'Word not found'
output.insert(0.0,textin)
def play():
text = output.get("0.0", "end").strip("\n")
if text == "əsɔ́":
playsound("hoe.mp3")
elif text == "jam":
playsound("axe.mp3")
elif text == "ɨghə́":
playsound("eye.mp3")
else:
# If there is no sound file for the translation:
playsound("eze.mp3")
#heading
lab0=Label(root,text='Translate English Words to Meta\'',bg="#35424a",fg="silver",font=
('none 11 bold'))
lab0.place(x=0,y=2)
#Entry field
ent=Entry(root,width=15,font=('Times 18'),textvar=textin,bg='white')
ent.place(x=30,y=30)
#focus on entry widget
ent.focus()
#Search button
but=Button(root,padx=1,pady=1,text='Translate',command=clk,bg='powder blue',font=('none 18
bold'))
but.place(x=60,y=90)
#press ENTER key to activate Translate button
root.bind('<Return>', returnPressed)
#output field
output=Text(root,width=15,height=1,font=('Times 18'),fg="black")
output.place(x=30,y=170)
#play button
play_button=Button(root,padx=1,pady=1,text='Play',command=play,bg='powder blue',font=('none
10 bold'))
play_button.place(x=100,y=210)
#prevent sizing of window
root.resizable(False,False)
#Dictionary
exlist={
"hat":"ɨ̀də̀m",
"hoe":"əsɔ́",
"honey":"jú",
"chest":"ɨgɔ̂",
"eye":"ɨghə́",
"ear":"ǝ̀tǒŋ",
"axe":"jam"
}
root.mainloop()
Since your code has a lot of dependency, it cannot be run on another system, so here is a common example which you should be able to implement to your code easily:
from tkinter import *
root = Tk()
def popup(event):
try:
menu.tk_popup(event.x_root,event.y_root) # Pop the menu up in the given coordinates
finally:
menu.grab_release() # Release it once an option is selected
def paste():
clipboard = root.clipboard_get() # Get the copied item from system clipboard
e.insert('end',clipboard) # Insert the item into the entry widget
def copy():
inp = e.get() # Get the text inside entry widget
root.clipboard_clear() # Clear the tkinter clipboard
root.clipboard_append(inp) # Append to system clipboard
menu = Menu(root,tearoff=0) # Create a menu
menu.add_command(label='Copy',command=copy) # Create labels and commands
menu.add_command(label='Paste',command=paste)
e = Entry(root) # Create an entry
e.pack(padx=10,pady=10)
e.bind('<Button-3>',popup) # Bind a func to right click
root.mainloop()
I have explained it with comments to understand on-the-go, nothing complicated. The menu just pops up when you right click on the entry as the function is binded to the entry alone. I think, without clipboard_clear() it would append all the items in the tkinter clipboard to the system clipboard.
I have a problem to detect/check button press in python tkinter !
I have a variable click i want that if my button is clicked then it becomes True
for ex:
this is my code:
buttonClicked=False
myButton=Button()
I want something like this:
if myButton is pressed:
buttonClicked=True
Thanks for your help!
I am not aware of any internal tkinter method to check if a button is pressed.
However you could connect the Button with a function that changes the value of a global variable, like in the following:
from Tkinter import *
master = Tk()
def callback():
global buttonClicked
buttonClicked = not buttonClicked
buttonClicked = False # Bfore first click
b = Button(master, text="Smth", command=callback)
b.pack()
mainloop()
The code, changes the variable value from False to True (or reverse) every time you press the button.
I think that you could make a function to change the value of buttonClicked, and, when the button is clicked, it executes that function (whose only purpose is to change the value of buttonClicked).
The complete code could go as follows:
from tkinter import *
buttonClicked = False
def changeValue():
if buttonClicked:
buttonClicked=False
if not buttonClicked:
buttonClicked=True
tk = Tk()
btn = Button(tk, text="Put whatever text you want here, to tell the person what pressing the button will do", command=changeValue())
btn.pack()
If this answer help, I would appreciate you tell me! :).
This is a changed/edited version, with a loop for logic that changes the value of buttonClicked. In the part of code that says "if not buttonClicked:" you could change to an "else:" statement. #
Try this:
from tkinter import *
value = 1
def change_value():
global value
value -= 1
if value == 0:
print("button pressed")
value = 1
else:
pass
tk = Tk()
btn = Button(tk, text="your_text", command=change_value)
btn.pack()
Just put the code you want to run inside a function like this:
def when_clicked():
#code you want here
button = Button(window,command=when_clicked)
(may be a bit late but oh well)
So I'm writing an app in Python 3.6, but I can't seem to find an answer on how to get the value of a messagebox answer (Yes or No).
fileSavedExit = True
def msgbox1():
if fileSavedExit == True:
root.destroy()
if fileSavedExit == False:
messagebox.askyesno('Save File ?','Do you want to save the file first?')
Something like that. I'm looking for code that would save the answer ('Yes' or 'No'). Would be thankful if anyone would help me. :O
askyesno returns True if the answer was "Yes" and False if the answer was "No". You can simply filter it with if/else.
Example
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
import tkinter.messagebox as tkmb
except ImportError:
import Tkinter as tk
import tkMessageBox as tkmb
def ask():
response = tkmb.askyesno("Messagebox Title", "Is this it?")
global button
if response: # If the answer was "Yes" response is True
button['text'] = "Yes"
else: # If the answer was "No" response is False
button['text'] = "No"
if __name__ == '__main__':
root = tk.Tk()
button = tk.Button(root, text="Ask...", command=ask)
button.pack()
tk.mainloop()