How to continue a message box? - python

I want to write a code that continues the message box after receiving an answer.
for example: If they answer yes they get another message box, and same applies for no.
I'm not sure how to word it correctly i hope it makes sense.
I've tried with this:
import tkinter
import tkinter.messagebox
tkinter.messagebox.askyesno(title = "Reginának" , message = "Mizu?")
answer = (tkinter.messagebox.askyesno = "yes")
if answer != "yes"
tkinter.messagebox.showwarning(title = "Reginának" , message = "Persze")
Although i do know that it's not right i was just trying to do something with my limited knowledge :))

Try this.
Code:
from tkinter import *
from tkinter import messagebox
ws = Tk()
ws.title('Python Guides')
ws.geometry('300x200')
ws.config(bg='#5FB691')
res = messagebox.askquestion('Reginának', '"Mizu?')
if res == 'yes':
messagebox.showinfo('Reginának', 'Persze')
elif res == 'no':
messagebox.showinfo('Reginának', 'You must be a Pele\'s fan.')
else:
messagebox.showwarning('error', 'Something went wrong!')
ws.mainloop()

Related

Python in Telegram. Problem with telebot library

Hello everyone! I need an advice for better understanding of Python's structure and syntax. No idea what's goin on.
Here is my code:
import telebot
import random
import time
from telebot import types
bot = telebot.TeleBot('token_name')
#bot.message_handler(commands=['start'])
def website(message):
markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=3)
war = types.KeyboardButton('A')
star = types.KeyboardButton('B')
markup.add(war, star)
bot.send_message(message.chat.id, 'CHOOSE:', reply_markup=markup)
#bot.message_handler(content_types=['text'])
def func(message):
if (message.text == "A"):
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
btn1 = types.KeyboardButton("1")
btn2 = types.KeyboardButton("2")
btn3 = types.KeyboardButton("3")
markup.add(btn1, btn2, btn3)
bot.send_message(message.chat.id, text="CHOOSE YOUR:", reply_markup=markup)
Everything is ok before this part:
elif (message.text == "B"):
markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=3)
war = types.KeyboardButton('THIS')
star = types.KeyboardButton('THIS THIS')
markup.add(war, star)
bot.send_message(message.chat.id, 'CHOOSE:', reply_markup=markup)
#bot.message_handler(commands=['THIS THIS'])
def website (message):
markup = types.InlineKeyboardMarkup()
markup.add(types.InlineKeyboardButton("1"))
bot.send_message(message.chat.id, 'CODE OF YOUR ORDER: №' + str(random.randint(10000, 99999)) +'<b>PAY</b>',parse_mode="html", reply_markup=markup
)
bot.polling(none_stop=True)
I expected result with Inline.Keyboard in message (example in picture №3). And also random number. In PyCharm i have clear terminal (no warnings, no errors). And Telegram without reply. No idea how i can fix this. I need button '1' inside message and random number. I think there is a conflict, because code already has [text] early, but still i can't fix this.
enter image description here
enter image description here
enter image description here

Python try and except bug (probably)

I've worked with little personal assistant project lately and now I'm facing this problem/bug and I can't get over it.
Here's part of my code:
import os
import sys
from colorama import Fore, Back, Style
import random
from os import system
from src import commands
system("title Assistant")
actions = {
"open":["pubg", "dota", "origins", "spotify", "dogs"],#"open":{["o"]:["pubg", "dota", "origins", "spotify", "dogs"]},
"hue":["1"],
"clear":"",
"hiber":"",
"shutdown":""
}
class MainClass:
#
logo1 = Fore.CYAN + """Not essential"""
logo2 = Fore.CYAN + """Not essential"""
errorcode = "Something went wrong :("
def getCommand(self):
cmd = input(Fore.MAGENTA + "Assistant > " + Fore.CYAN)
print("cmd: " + cmd)
self.checkCommand(cmd)
def checkCommand(self, cmd):
actions = commands.Commands().actions
words = cmd.lower().split()
print("Words: " + ' '.join(words))
found = False
ekasana = ""
par = ""
print("running if " + words[0] + str(words[0] == "q"))
#Here's the problem. After I imput 'clear', which clear's the screen and runs mainInterface(2.0, randomthing), this if does not work.
# Here's the output
# Not essentialv 2.0
# By Dudecorn
# Assistant > q
# cmd: q
# Words: q
# running if qTrue
# self.errorcode
# clear
# ['clear']
# Assistant >
# Why is is that clear command staying there? I am so confused right now.
# Read line 68
if words[0] == "q":
quit()
sys.exit()
for word in words:
word = ''.join(word)# Sorry about the mess
print(word)
# Check for action without parameters
if word in actions and actions[word] == "" and found == False:
try: # I'm pretty sure that this part of code is causing the problem
# If you remove try and except, and leave just lines 70 and 71, code works as line 58 if statement's value is true.
# This is in the another file -> getattr(commands.Commands, word)(self)
self.mainInterface(2.0, random.randint(1, 2))
break
except:
print("self.errorcode")
print(word)
print(words)
# Check for action that has parameters
elif word in actions and not actions[word] == "" and found == False:
ekasana = word
found = True
# Check for parameters
elif not ekasana == "" and found == True:
for n in actions[ekasana]:
if n == word:
par = word
try:
getattr(commands.Commands, ekasana)(self, par)
except:
print(self.errorcode)
else:
print("Command not found")
self.getCommand()
def mainInterface(self, v, logo):
os.system('cls' if os.name == 'nt' else 'clear')
if logo == 1:
print(self.logo1+"v "+str(v)+"\n By Dudecorn")
else:
print(self.logo2+"v "+str(v)+"\n By Dudecorn")
self.getCommand()
And here's the main file
import test
import random
def main():
m = test.MainClass()
m.mainInterface(2.0, random.randint(1,2))
main()
So, when you run the code and first input 'clear' and then q the if statement won't execute. And I wonder why. I also noticed that if you remove try and except from first if statement after loop the code works perfectly. I could remove them but it wouldn't answer my question, why isn't the code working. Also removing try and except from the file should not have any effect on how the first if statement executes, as it comes up later in the code.
Sorry about bad english as it isn't my main language, and thank you for your answers. Also I want to apologize for that huge mess in the code.
I am not sure if this is the answer that you are looking for, but it may be useful to check.
From the code below,
def main():
m = test.MainClass()
m.mainInterface(2.0, random.randint(1,2))
main()
, I see that by running main(), you also run the m.mainInterface function.
Now..you may want to check this :
The method mainInterface will eventually call the method getCommand, which will eventually call checkCommand, which..will encounter the try block in the for word in actions loop, and inside this try block..there is a calling of mainInterface again..so this process will be keep repeating.

I'm trying to create a tkinter output window for a text based application

I have a script that continually takes in text and outputs text (its a text based game)
I would like to run it through a tkinter GUI as opposed to the console
Python : Converting CLI to GUI
This question perfectly answers how to convert "print" into a GUI insert.
The problem is that my game obviously runs through a ton of loops, and that screws up the "app.mainloop()" because it either never runs (and then the GUI never shows up) or you run it first, and it doesn't let anything else run.
I suppose I could try and and stagger these loops somehow, but that seems very hackish. I could also try to modify my entire codebase to run inside the app.mainloop(), but what I really think I need is multiple threads. Problem is, I have no idea how to make that work.
There are a few other questions, but they either don't work or don't make much sense:
Tkinter with multiple threads
Run process with realtime output to a Tkinter GUI
Thanks.
Edit: extremely simplified code:
def moveNorth():
print('You have moved north')
def interpreter(command):
if command == 'go north':
moveNorth()
else:
print('invalid command')
def listener():
playerchoice = sys.stdin.readline().strip()
return playerchoice
if __name__ == '__main__':
print('Welcome')
while playing:
interpreter(listener())
I think you might be making it more complicated than it needs to be.
For Tkinter at least it is very simple change console interactions into a GUI interaction instead.
The simplest example I can give is to use an Entry field for user input and a Text widget for the output.
Here is a simple example of a console based game being moved to a GUI using Tkinter.
Console number guessing game:
import random
print("simple game")
print("-----------")
random_num = random.randint(1, 5)
print(random_num)
x = True
while x == True:
#Input for user guesses.
guess = input("Guess a number between 1 and 5: ")
if guess == str(random_num):
#Print answer to console.
print("You win!")
x = False
else:
print("Try again!")
Here is the Tkinter GUI example of the same game:
import tkinter as tk
import random
root = tk.Tk()
entry_label = tk.Label(root, text = "Guess a number between 1 and 5: ")
entry_label.grid(row = 0, column = 0)
#Entry field for user guesses.
user_entry = tk.Entry(root)
user_entry.grid(row = 0, column = 1)
text_box = tk.Text(root, width = 25, height = 2)
text_box.grid(row = 1, column = 0, columnspan = 2)
text_box.insert("end-1c", "simple guessing game!")
random_num = random.randint(1, 5)
def guess_number(event = None):
#Get the string of the user_entry widget
guess = user_entry.get()
if guess == str(random_num):
text_box.delete(1.0, "end-1c") # Clears the text box of data
text_box.insert("end-1c", "You win!") # adds text to text box
else:
text_box.delete(1.0, "end-1c")
text_box.insert("end-1c", "Try again!")
user_entry.delete(0, "end")
# binds the enter widget to the guess_number function
# while the focus/cursor is on the user_entry widget
user_entry.bind("<Return>", guess_number)
root.mainloop()
As you can see there is a bit more code for the GUI but most of that is the GUI design.
The main part that you need to change is the use of entry vs input for your answers and the use of insert vs print for your response. The rest is really just design stuff.
If you want to keep the questions on a continuous nature you can update the label with a new question or you could even use tkinters askstring function for each new question. There are many options.
the main thing is getting the value of the user answer, using that answer to test with the question, then printing the results to the text box.

TkInter Entry Box Being Disabled

I'm working on a GUI Python program using Tkinter.
I have a function that is called when a button is pressed (and when the program is loaded). The program is currently unfinished and only checks data validation at this current point. As the default entry is current invalid, it throws an error.
However, after this point, the entry box is disabled and will not let me enter any data. I cannot figure out why this is happening and I was wondering if someone could tell me the reason so I can work on a solution.
Thanks
import sys
import random
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
root = Tk()
root.title("COSC110 - Guessing Game")
hint = StringVar()
guesses = []
guess_input = ''
def loadWordList(filename): #Load the words from a file into a list given a filename.
file = open(filename, 'r')
line = file.read().lower()
wordlist = line.split()
return wordlist
word = random.choice(loadWordList('words.txt'))
def getHint(word, guesses): #Get hint function, calculates and returns the current hint.
hint = ' '
for letter in word:
if letter not in guesses:
hint += '_ '
else:
hint += letter
return hint
def guessButton(guess, word, guesses):
guess = str(guess_input)
guess = guess.lower()
if not guess.isalpha():
is_valid = False
elif len(guess) !=1:
is_valid = False
else:
is_valid = True
while is_valid == False:
messagebox.showinfo("Error:","Invalid input. Please enter a letter from a-z.")
break
hint.set(getHint(word, guesses))
return hint
label_instruct = Label(root, text="Please enter your guess: ")
label_instruct.grid(row=1,column=1,padx=5,pady=10)
guess_input = Entry(root,textvariable=guess_input)
guess_input.grid(row=1, column=2)
guess_button = Button(root, text="Guess", width=15, command=guessButton(guess_input,word,guesses))
guess_button.grid(row=1, column=3,padx=15)
current_hint = Label(root, textvariable=hint)
current_hint.grid(column=2,row=2)
label_hint = Label(root, text="Current hint:")
label_hint.grid(column=1,row=2)
label_remaining = Label(root, text="Remaining guesses: ")
label_remaining.grid(column=1,row=3)
root.mainloop() # the window is now displayed
Any tips are appreciated.
There are two apparent problems.
Firstly, you shouldn't use
guess_button = Button(root, text="Guess", width=15, command=guessButton(guess_input,word,guesses))
because you can't call a function with arguments on the command config.
My suggestion would be to take a look here and use one of the proposed methods, I particularly like the one using functools and partial:
from functools import partial
#(...)
button = Tk.Button(master=frame, text='press', command=partial(action, arg))
with action being the function you want to call and arg the parameters you want to call separated by a comma.
Secondly, you are using
guess = str(guess_input)
which doesn't return the Entry typed text, use instead
guess = guess_input.get()
PS: Albeit not directly related to your question, you should use
if var is False:
instead of
if var == False:

I have an error in python with tkinter and need help(school project)

I have to create a little text adventure for school in python.
To detect keyboard inputs I decided to use tkinter and disable the window.
All is working fine but if I try to calculate with a variable after a key was pressed, I get the following error...This is the error message
This is the script I am using(I don't have much experience with python...)
import os
import sys
import tkinter
menueeintraege = ["Start", "Steuerung", "Credits", "Beenden"]
index = 0
def menueaufbauen():
os.system("cls")
print("Menue")
print("")
print("")
for i in range(4):
if i == index:
print(menueeintraege[i] + "<")
else:
print(menueeintraege[i])
menueaufbauen()
def startgame():
os.system("game.py");
def steuerung():
os.system("cls")
print("Steuerung")
print("")
print("Norden = Pfeiltaste Hoch")
print("Sueden = Pfeiltaste Runter")
print("Osten = Pfeiltaste Rechts")
print("Westen = Pfeiltaste Links")
print("Bestaetigen = Enter")
def credits():
os.system("cls")
print("Credits")
print("")
print("Jannik Nickel")
print("Thomas Kraus")
print("")
def exitgame():
sys.exit()
def menueauswahl(taste):
print(taste)
if taste == "Up":
if index > 0:
index -= 1
print(index)
elif taste == "Down":
if index < 3:
index += 1
menueaufbau()
def tasteneingabe(event):
tastenname = event.keysym
menueauswahl(tastenname)
fenster = tkinter.Tk()
fenster.bind_all('<Key>', tasteneingabe)
fenster.withdraw()
fenster.mainloop()
I think the mistake have to be in the last part of the script, I hope someone here knows a solution because it's really important for school.
Thanks for any help
(I'm using Visual Studio 2015)
Okay so I caught a couple of errors. The first is that you are referencing a global variable (index) inside of a function. To do that, you need to tell python that you are using a global variable.
def menueauswahl(taste):
global index
print(taste)
And also you need to change the function name in line 61 to menuaufbauen().

Categories

Resources