So I have this code:
from tkinter import *
import re
master = Tk()
e1 = Entry(master)
def confirmit():
s = re.findall(r'\b\d+\b', e1.get())
if e1.get() == "Whoscreator":
vyvod.configure(text="Kewbin")
if e1.get() == "Whatscreatorsrealname":
vyvod.configure(text="Peťo Letec")
if e1.get() == "/give " + (what should I type here?):
vyvod.configure(text= s)
vyvod = Label(master, text="First Name")
confirmer = Button(text="Confirm", command = confirmit)
e1.pack()
vyvod.pack()
confirmer.pack()
mainloop()
I have an entry bar.
And I want this for example:
If I type in the bar /give 1000 it will type the number 1000 into Label vyvod. And I want this to work with any number i type after /give
The simplest solution is to split the string on a space, examine the first word, and do whatever is appropriate with the rest.
value = e1.get()
first, rest = value.split(" ", 1)
if first == "/give":
vyvod.configure(text=rest)
Related
I am a beginner in python I would like to create an interface which allows to enter text (number) and to cut the output with print to separate the different elements
for example
my texte = NNNNNNNNNKKVVVVVECPM
in output I would like = NNNNNNNNN KK VVVVV E C P M
thank you for your help good day
If you just want to insert spaces between sequences, try this:
text = "NKNNPPOUSSEVNN"
l=[]
for i,char in enumerate(text):
try:
if text[i]==text[i+1]:
l.append(char)
else:
if i==0: l.append(str(text[i])+" "+str(text[i+1]))
else: l.append(" "+str(text[i+1]))
except: pass
print("".join(l))
This gives:
N K NN PP O U SS E V NN
If you want to group the text on characters and then print out, use itertools:
import itertools
text = "NKNNPPOUSSEVNN"
for i,grp in itertools.groupby(sorted(text)):
print("".join(grp),end=" ")
This gives:
E K NNNNN O PP SS U V
hello thank you for the answer my main problem is that my numbers are separated by check I can display my text but I want separation
voici mon programe
#!/usr/bin/python3
from tkinter import *
class MyWindow(Tk):
def __init__(self):
Tk.__init__(self)
self.__code = StringVar()
label = Label( self, text="Scanner le code barre:")
label.pack()
code = Entry(self, textvariable=self.__code )
code.focus_set()
code.pack()
button = Button( self, text="Vérifier!", command=self.doSomething)
button.pack()
self.geometry( "400x300" )
self.title( "Entry widget usage" )
def doSomething(self):
print( "ticket restaurant " + self.__code.get() )
window = MyWindow()
window.mainloop()
i am wanting to make it so it gets the input from the user and changes it but its only changing the last letter
i have many times to correct this but it doesn't work for some reason
from tkinter import *
import random
window = Tk()
window.title("Enigma Ui")
lbl = Label(window, text='''Welcome
''',font=("Comic Sans", 16))
lbl.grid(column=0, row=0)
window.geometry('350x200')
def clicked():
res = "" + txt.get()
keyword5 = ["a"]
if any(keyword in res for keyword in keyword5):
lbl.configure(text= "h")
keyword6 = ["b"]
if any(keyword in res for keyword in keyword6):
lbl.configure(text= "j")
btn = Button(window, text="Encrypt", bg="light blue", command = clicked)
btn.grid(column=20, row=30)
txt =Entry(window,width=10)
txt.grid(column=14,row=30)
window.mainloop()
i want it to take user input and change all letters not just one
The problem is in your clicked function, when you call lbl.configure() you will always return just the single letter h or j.
Here's a possible different clicked function:
def clicked():
res = "" + txt.get()
# define a dictionary to match keywords to their encrypted letter
keywords = {'a': 'h',
'b': 'j'}
new_label_value = res
# use the string replace function to encrypt matching letters in a loop
for keyword, encrypted in keywords.items():
new_label_value = new_label_value.replace(keyword, encrypted)
lbl.configure(text=new_label_value)
This will overwrite the keyword letters in a loop and return a new string.
Tic-tac-toe game using python tkinter is not working correctly.
Tic-tac-toe structure is correct. I just want to change the click event.
Only button9 output shown when click to any button
Every time I click any button this output is shown
from tkinter import *
bclick = True
tk = Tk()
tk.title("Tic Tac toe")
tk.geometry("300x400")
n = 9
btns = []
def ttt(button):
global bclick
print(button)
if button["text"] == "" and bclick == True:
print("if")
button.config(text="X")
bclick = False
elif button["text"] == "" and bclick == False:
print("else")
button["text"] = "0"
bclick = True
for i in range(9):
btns.append(Button(font=('Times 20 bold'), bg='white', fg='black', height=2, width=4))
row = 1
column = 0
index = 1
print(btns)
buttons = StringVar()
for i in btns:
i.grid(row=row, column=column)
i.config(command=lambda: ttt(i))
print(i, i["command"])
column += 1
if index % 3 == 0:
row += 1
column = 0
index += 1
tk.mainloop()
Common misstake. The lambda function is using the last value assigned to i so every lambda will use i=.!button9. change the lambda function to:
i.config(command=lambda current_button=i: ttt(current_button))
which will make lambda use the value of i when the lambda was created.
if option == "1":
with open("sample.txt","r") as f:
print(f.read())
numbers = []
with open("sample2.txt","r") as f:
for i in range(9):
numbers.append(f.readline().strip())
print(numbers)
from random import randint
for i in range(9):
print(numbers[randint(0,8)])
from tkinter import *
def mhello():
mtext = ment.get()
mLabel2 = Label(test, text=mtext).pack()
return
test = Tk()
ment = StringVar()
test.geometry('450x450+500+10')
test.title('Test')
mlabel = Label(test, text='Time to guess').pack()
mbutton = Button(test, text='Click', command = mhello).pack()
mEntry = Entry(test, textvariable=ment).pack()
test.mainloop()
from tkinter import *
def mhello():
my_word = 'HELLO'
mtext = ment.get()
if my_word == mtext:
mLabel2 = Label(test, text='Correct').pack()
else:
mLabel2 = Label(test, text='Incorrect').pack()
return
test = Tk()
ment = StringVar()
test.geometry('450x450+500+300')
test.title('Test')
def label_1():
label_1 = Label(test, text='Hello. Welcome to my game.').pack()
def label_2():
label_2 = Label(test, text='What word am I thinking of?').pack()
button_1 = Button(test, text='Click', command = mhello).pack()
entry_1 = Entry(test, textvariable=ment).pack()
label_1()
test.after(5000, label_2)
test.mainloop()
from tkinter import *
from random import shuffle
game = Tk()
game.geometry('200x200')
game.grid()
game.title("My Game")
board = [1, 2, 3, 4, 5, 6, 7, 8, 9]
def board_1():
board1 = []
k = 0
for i in range(3):
for j in range(3):
board1.append(Label(game, text = board[k]))
board1[k].grid(row = i, column = j)
k +=1
def board_2():
shuffle(board)
board2 = []
k = 0
for i in range(3):
for j in range(3):
board2.append(Label(game, text = board[k]))
board2[k].grid(row = i, column = j)
k +=1
board_1()
game.after(5000, board_2)
game.mainloop()
#2nd Option
elif option == "2":
print ("You have chosen option 2. Well Done, You Can Type! XD")
The bit that has the Syntax Error is the 1st elif statement (2nd Option). Ignore all the code prior to this if necessary (it is there for context). Whenever I run the code it says that there is a syntax error and just positions the typing line (I don't know what it's called) at the end of the word elif.
This is a simple fix, with if else statements you need to have a closing ELSE and in this case there is not so when your program runs it sees that theres a lonely if without its else :)
if option == "1":
elif option == "2":
else:
'do something else in the program if any other value was recieved'
also a switch statement can be used here so it does not keep checking each condition and just goes straight to the correct case :D
The problem is that your block is separated from the first if-statement, where it actually belongs to. As it is, it follows the game.mainloop() statement, and adds an unexpected indentation. Try to rearrange your code like so:
if option == "1":
with open("sample.txt","r") as f:
print(f.read())
numbers = []
with open("sample2.txt","r") as f:
for i in range(9):
numbers.append(f.readline().strip())
print(numbers)
from random import randint
for i in range(9):
print(numbers[randint(0,8)])
elif option == "2":
print ("You have chosen option 2. Well Done, You Can Type! XD")
[ Rest of the code ]
So i have this code here in python 3.3, it cyphers text with the ceaser cypher.
What i need to know is how do i make a script that will convert it back from the original so that the person i send it too can read it.
message = input("Input: ")
key = 11
coded_message = ""
for ch in message:
code_val = ord(ch) + key
if ch.isalpha():
if code_val > ord('z'):
code_val -= ord('z') - ord('a')
coded_message = coded_message + chr(code_val)
else:
coded_message = coded_message + ch
# print ("Input: " + message)
print ("Output: " + coded_message)
One more thing, I plan to be putting this is a tkinter message box, with the two entry fields used for the input and output. one field should be used to type what i want to convert and the other should be used to show what the text looks like after it has been crypted. The button should start the encryption. here is the code:
import sys
from tkinter import *
def mHello():
mLabel = Label(mGui,text = input("Hello World"))
mLabel.grid(row=3, column=0,)
mGui = Tk()
ment = StringVar()
mGui.geometry("450x450+250+250")
mGui.title("My TKinter")
# input label
mLabel = Label(mGui,text = "Input",)
mLabel.grid(row=1,column=0,)
# output label
mLabeltwo = Label(mGui,text = "Input",)
mLabeltwo.grid(row=2,column=0,)
# convert button
mButton = Button(text = "Convert",command = mHello)
mButton.grid(row=3,column=0)
# input entry
mEntry = Entry(mGui,textvariable=ment)
mEntry.grid(row=1,column=1)
# output entry
mEntryTwo = Entry(mGui,textvariable=ment)
mEntryTwo.grid(row=2,column=1)
mGui.mainloop()
By the way i am only 15 and this is my 2nd day learning python.
Some credit goes to sources on this forum that have provided me with some code snippets
Thank-you in advance guys!
Before i say anything else you should be aware that minds much greater the mine have advised against writing your own cypher script for anything other then learning
If you want them to be able to decode your code then provide them with a key. so in your case:
s maps to h
t maps to i
f maps to t
I hope this code illustrates my suggestion:
In [1]: from cyro import your_cyrptic_function
In [2]: key = {'s':'h', 't':'i', 'f':'t'}
In [3]: secret_word = your_cyrptic_function('hit')
In [4]: decyrpted_secret_word = ''
In [5]: for letter in secret_word:
decyrpted_secret_word += key[letter]
...:
In [6]: print(decyrpted_secret_word)
hit
For the code above i turned your original code into a function:
def your_cyrptic_function(secret):
message = secret
key = 11
coded_message = ""
for ch in message:
code_val = ord(ch) + key
if ch.isalpha():
if code_val > ord('z'):
code_val -= ord('z') - ord('a')
coded_message = coded_message + chr(code_val)
else:
coded_message = coded_message + ch
# print ("Input: " + message)
return coded_message
there are several great ways to do this in python. If your interested in cyptopgraphy then check out Udacities class cs387 applied cryptography