I'd like to make a program which takes an integer from user and makes as many entries in a Tkinkter window. Then It'll make a graph base on them but for now I do not know how to make as many entries in my window. I tried something like this below but It does not work. Please help.. edit: oh and It's PyDev for Eclipse python 2.75
# -*- coding: utf-8 -*-
#import matplotlib.pyplot as mp
import Tkinter as T, sys
def end():
sys.exit()
def check():
z = e.get()
try:
z = int(z)
e.config(bg = 'green')
e.after(1000, lambda: e.config(bg = 'white'))
x = []
for i in (0,z):
x.append(e = T.Entry(main, justify = 'center'))
x[i].pack()
except:
e.config(bg = 'red')
e.after(1000, lambda: e.config(bg = 'white'))
z = 0
main = T.Tk()
main.title('something')
main.geometry('600x600')
main.config(bg = "#3366ff")
e = T.Entry(main,justify = 'center')
l = T.Label(main,text = 'Give me an N =',bg = '#3366ff')
b1 = T.Button(main, text = 'OK', command = check)
b = T.Button(main,text = 'Zakończ', command = end)
l.pack()
e.pack()
b1.pack()
b.pack()
main.mainloop()
Make youre for-loop look like this:
for i in range(0,z):
x.append( T.Entry(main, justify = 'center'))
x[i].pack()
you need to use range because when you dont it is only iterating through twice because it thinks its iterationg through a 2 item tuple instead of a list of numbers
also get rid of the e = so that it is just appending a new entry each time
Related
What I am trying to achieve is something like this:
But instead, what I am getting is this:
This is the structure:
The file that's getting the JSON data, called bitmex.py
import requests
def get_contracts():
response_object = requests.get('https://www.bitmex.com/api/v1/instrument/active')
contracts = []
for contract in response_object.json():
contracts.append(contract['symbol'])
return contracts
print(get_contracts())
And this is the main.py that is populating the data into a Grid:
import tkinter as tk
from bitmex import get_contracts
if __name__ == '__main__':
bitmex_contracts = get_contracts()
root = tk.Tk()
root.title("Bitmex Contracts")
x = 0
y = 0
for contract in bitmex_contracts:
label_widget = tk.Label(root, text=contract, borderwidth=1, relief=tk.SOLID, width=13).grid(row=x, column=y, sticky='ew')
if x >= 4:
y += 1
x = 0
else:
x += 1
root.geometry('800x600')
root.mainloop()
As you'll see the problem I am facing is that the data is getting one underneath each other but not on a grid but superimposed instead.
The version of Python I am using is v.3.9.7 and
Tkinter v.8.6
I am learning tkinter and wrote some test code for combobox, but the initial display does not match my expectation.
Here is the code.
#!python3
r""" combobox.py
https://tkdocs.com/tutorial/widgets.html#combobox
"""
from tkinter import *
from tkinter import ttk
root = Tk()
root.title("Combobox")
s = StringVar(value="On") # default value is ''
b = BooleanVar(value=True) # default is False
i = IntVar(value=10) # default is 0
d = DoubleVar(value=10.5) # default is 0.0
def comboboxSelected(*args):
print("comboboxSelected({})".format(args))
print(" s = {}".format(s.get()))
cs.selection_clear()
print(" b = {}".format(b.get()))
cb.selection_clear()
print(" i = {}".format(i.get()))
ci.selection_clear()
print(" d = {}".format(d.get()))
cd.selection_clear()
cs = ttk.Combobox(root, textvariable=s)
cs.bind('<<ComboboxSelected>>', comboboxSelected)
cs['values'] = ('On', 'Off')
cs.grid()
cb = ttk.Combobox(root, textvariable=b)
cb.bind('<<ComboboxSelected>>', comboboxSelected)
cb['values'] = (True, False)
cb.grid()
ci = ttk.Combobox(root, textvariable=i)
ci.bind('<<ComboboxSelected>>', comboboxSelected)
ci['values'] = (10, 1)
ci.grid()
cd = ttk.Combobox(root, textvariable=d)
cd.bind('<<ComboboxSelected>>', comboboxSelected)
cd['values'] = (10.5, 2.3)
cd.grid()
root.mainloop()
The initial display looks has a 1 in the boolean's combobox.
After I select, it displays as expected.
Why is it displaying as 1 on initial load and is there anything I can do to make it show as True instead?
I am a high school student trying to create a quiz program that selects random true or false questions.
What I want to do is get the label AnswerQuestionPageText2 (with the text variable AnswerQuestionPageText2Variable) reload when the button AnswerQuestionPageButton4 is pressed. Before it is pressed, it should read Please click 'reload question'. However, AnswerQuestionPageText2 doesn't show at all.
Thanks for any help. But please, don't send hate to me. I have already tried asking on stack overflow and that was all I got.
Code:
from tkinter import *
from tkinter.font import *
from tkinter import messagebox
import random
#variables
IQ = 0
int(IQ)
#lists
TrueQuestions = [
'true question 1',
'true question 2',
'true question 3',]
current_question = random.choice(TrueQuestions)
#command defines
def MainMenuButton1Command():
MainMenu.withdraw()
AnswerQuestionPage.deiconify()
def MainMenuButton2Command():
pass
def MainMenuButton3Command():
pass
def MainMenuButton4Command():
pass
def MainMenuButton5Command():
quit()
def AnswerQuestionPageButton1Command():
AnswerQuestionPage.withdraw()
MainMenu.deiconify()
def AnswerQuestionPageButton2Command():
pass
def AnswerQuestionPageButton3Command():
pass
def AnswerQuestionPageButton4Command():
current_question = random.choice(TrueQuestions)
AnswerQuestionPageText2variable.set("Question: "+str(current_question))
AnswerQuestionPageText2variable.get()
#MainMenu
MainMenu = Tk()
MainMenu.attributes("-fullscreen", True)
MainMenu.title("IQ extreme Main Menu")
MainMenu.configure(bg="blue")
BigFont = Font(family="Tahoma",size=48,weight="bold")
SmallFont = Font(family="Tahoma",size=24)
TinyFont = Font(family="Tahoma",size=18)
MainMenuText1 = Label(MainMenu,bg="blue",fg="black",font=TinyFont,text="MAIN MENU")
MainMenuText1.place(x=1130,y=0)
MainMenuText2 = Label(MainMenu,bg="blue",fg="black",font=SmallFont,text="IQ")
MainMenuText2.place(x=400,y=75)
MainMenuText3 = Label(MainMenu,bg="blue",fg="black",font=BigFont,text="EXTREME")
MainMenuText3.place(x=500,y=120)
MainMenuText4 = Label(MainMenu,bg="blue",fg="black",font=TinyFont,text="Current IQ: "+str(IQ))
MainMenuText4.place(x=575,y=275)
MainMenuButton1 = Button(MainMenu,bg="white",fg="black",font=TinyFont,text="Start",width=20,command=MainMenuButton1Command)
MainMenuButton1.place(x=525,y=400)
MainMenuButton2 = Button(MainMenu,bg="white",fg="black",font=TinyFont,text="Upgrade",width=20,command=MainMenuButton2Command)
MainMenuButton2.place(x=525,y=475)
MainMenuButton3 = Button(MainMenu,bg="white",fg="black",font=TinyFont,text="See Data",width=20,command=MainMenuButton3Command)
MainMenuButton3.place(x=525,y=550)
MainMenuButton4 = Button(MainMenu,bg="white",fg="black",font=TinyFont,text="How to play",width=20,command=MainMenuButton4Command)
MainMenuButton4.place(x=25,y=950)
MainMenuButton5 = Button(MainMenu,bg="red",fg="black",font=TinyFont,text="Quit",width=5,command=MainMenuButton5Command)
MainMenuButton5.place(x=0,y=0)
#AnswerQuestionPage
AnswerQuestionPage = Tk()
AnswerQuestionPage.withdraw()
BigFont = Font(AnswerQuestionPage,family="Tahoma",size=48,weight="bold")
SmallFont = Font(AnswerQuestionPage,family="Tahoma",size=24)
TinyFont = Font(AnswerQuestionPage,family="Tahoma",size=18)
AnswerQuestionPage.attributes("-fullscreen", True)
AnswerQuestionPage.title("IQ extreme")
AnswerQuestionPage.configure(bg="blue")
AnswerQuestionPageText1 = Label(AnswerQuestionPage,bg="blue",fg="black",font=SmallFont,text="Current IQ: "+str(IQ))
AnswerQuestionPageText1.place(x=0,y=0)
AnswerQuestionPageText2variable = StringVar()
AnswerQuestionPageText2variable.set("Please click 'reload question'")
AnswerQuestionPageText2 = Label(AnswerQuestionPage,bg="blue",fg="black",font=BigFont,textvariable=AnswerQuestionPageText2variable)
AnswerQuestionPageText2.place(x=350,y=75)
AnswerQuestionPageButton1 = Button(AnswerQuestionPage,bg="white",fg="black",font=TinyFont,text="Home",width=5,command=AnswerQuestionPageButton1Command)
AnswerQuestionPageButton1.place(x=1205,y=5)
AnswerQuestionPageButton2 = Button(AnswerQuestionPage,bg="green",fg="black",font=BigFont,text="True",width=10,command=AnswerQuestionPageButton2Command)
AnswerQuestionPageButton2.place(x=120,y=500)
AnswerQuestionPageButton3 = Button(AnswerQuestionPage,bg="red",fg="black",font=BigFont,text="False",width=10,command=AnswerQuestionPageButton3Command)
AnswerQuestionPageButton3.place(x=760,y=500)
AnswerQuestionPageButton4 = Button(AnswerQuestionPage,bg="white",fg="black",font=TinyFont,text="Reload question",width=20,command=AnswerQuestionPageButton4Command)
AnswerQuestionPageButton4.place(x=500,y=0)
I am building a Python code that should read a text file using askopenfile in tkinter in Python. The text file is just a column of numbers:
300.0
250.0
250.0
250.0
250.0
270.61032473
289.91197172
290.23398559
275.90792547
263.86956625
264.8385967
My code is attached below:
from tkinter import *
from tkinter.ttk import *
import numpy as np
from tkinter.filedialog import askopenfile
root = Tk()
t=12
p=np.empty(t)
def open_file():
file = askopenfile(mode ='r', filetypes =[('all files', '*.*')])
if file is not None:
global x
x = file.read()
print(x)
global p
global count
#x=x.split('\n')
#count=0
#for row in x:
# i=float(row[0])#change from string to float type
# p[count]=i #updates x array
# count +=1 # increment of 1 to get the number of total values
#p=p.reshape(t,1)
#print(p)
return x
#print(p)
btn = Button(root, text ='Open', command = lambda:open_file())
btn.pack(side = TOP, pady = 10)
mainloop()
When I print x from the command window, the result is the following:
'300.0 \n300.0 \n250.0 \n250.0\n250.0\n250.0 \n270.61032473 \n289.91197172 \n290.23398559 \n275.90792547\n263.86956625 \n264.8385967'
Hence when I print x[0] for instance, the results is only: 3.
I actually want x[0] to be 300.0, x[1] to be 250.0, etc.
In addition to that, I want to convert them to numerical numbers not strings.
To parse the string x
x = '300.0 \n300.0 \n250.0 \n250.0\n250.0\n250.0 \n270.61032473 \n289.91197172 \n290.23398559 \n275.90792547\n263.86956625 \n264.8385967'
into a list of numbers, you could do:
x_as_list_of_numbers = [float(xx.strip()) for xx in x.split('\n')]
I'm creating a GUI with tkinter, in this GUI there are some entry widgets that the user has to fill in, and the inputs will be stored in a file.
The issue that I'm facing is that the user can't insert special characters like emojis in these entry widgets.
I found some ways to display them...:
converting a special character to the equivalent surrogate pair:
this '\U0001f64f'(🙏) to this '\ud83d\ude4f'
Python: Find equivalent surrogate pair from non-BMP unicode char
converting a special character to the equivalen javascript format:
this 😊 to this '\uD83D\uDE05'
Displaying emojis/symbols in Python using tkinter lib
... but I didn't find anything about my problem.
I thought about solving it by displaying near the entries a table with the emojis and the relative code to insert it in the entry instead of inserting the emoji directly, so something like this...:
1:🙏 2:😊 3:🔥 4:😃
...and have the user insert 1, 2, 3 or 4 instead of the emoji, but I don't think that this is a good way to solve the problem.
From my research, I understood that the problem is in the tkinter module and I was wondering if there was a way to overcome it.
# -*- coding: utf-8 -*-
from tkinter import *
def sumbit():
print(var.get())
root = Tk()
root.tk.call('encoding', 'system', 'utf-8')
var = StringVar()
entry = Entry(root, textvariable=var)
entry.pack()
button = Button(root, text="sumbit", command=sumbit)
button.pack()
root.mainloop()
This is an example of the problem, I have a window with an Entry widget where the user can insert an emoji, but if the user inserts an emoji, the code raises the following error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:/Users/mcara/PycharmProjects/1/python/1.py", line 5, in sumbit
print(var.get())
File "C:\Program Files\Python37-32\lib\tkinter\__init__.py", line 484, in get
value = self._tk.globalgetvar(self._name)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xed in position 0: invalid continuation byte
I'm working with Windows and Pyton 3.7
I have worked around this problem as this for now:
# -*- coding: utf-8 -*-
from tkinter import *
import tkinter.font as tkFont
# Dict with all the emojis
# it is made in this format --> EMOJI_NAME: EMOJI_SURROGATE_PAIR
emoji_dict = {
"GRINNING_FACE": '\ud83d\ude00',
"GRINNING_FACE_WITH_BIG_EYES": '\ud83d\ude03',
"GRINNING_FACE_WITH_SMILING_EYES": '\ud83d\ude04',
"BEAMING_FACE_WITH_SMILING_EYES": '\ud83d\ude01',
"GRINNING_SQUINTING_FACE": '\ud83d\ude06',
"GRINNING_FACE_WITH_SWEAT": '\ud83d\ude05',
"LAUGHING_ON_THE_FLOOR": '\ud83e\udd23',
"TEARS_OF_JOY": '\ud83d\ude02',
"SMILING_FACE_SLIGHTLY": '\ud83d\ude42',
"UPSIDE-DOWN_FACE": '\ud83d\ude43',
"WINKING_FACE": '\ud83d\ude09',
}
emoji_num_name = dict()
emoji_name_num = dict()
counter = 0
for key in emoji_dict:
emoji_num_name[counter] = key
emoji_name_num[key] = counter
counter += 1
def search(text):
for widget in emoji_frame.winfo_children():
if isinstance(widget, Button):
widget.destroy()
emoji_name_list = list(emoji_dict.keys())
emoji_name_list.sort()
if text == "" or text == " ":
creates_emojis()
else:
x = 10
y = 0
for emoji_name in emoji_name_list:
if emoji_name.startswith(text):
emoji_code = emoji_dict[emoji_name]
code_ = emoji_name_num[emoji_name]
emoji_button = Button(emoji_frame, text=emoji_code, borderwidth=0, font=customFont)
emoji_button.place(x=x, y=y)
emoji_button.bind("<Button-1>", lambda event, code=code_, var=sumbit_var: insert_emoji(var, ":-" + str(code) + "-:"))
if x <= 150:
x += 30
else:
x = 10
y += 30
emoji_frame.configure(widt=200, height=y+60)
def insert_emoji(var, code):
var.set(var.get() + code)
def creates_emojis():
x = 10
y = 0
for emoji_name in emoji_dict:
emoji_code = emoji_dict[emoji_name]
code_ = emoji_name_num[emoji_name]
emoji_button = Button(emoji_frame, text=emoji_code, borderwidth=0, font=customFont)
emoji_button.place(x=x, y=y)
emoji_button.bind("<Button-1>", lambda event, code=code_, var=sumbit_var: insert_emoji(var, ":-" + str(code) + "-:"))
if x <= 150:
x += 30
else:
x = 10
y += 30
emoji_frame.configure(widt=200, height=y+60)
def sumbit(text):
text = text.split(":-")
for index in range(len(text)):
word = text[index]
word = word.split("-:")
for index_ in range(len(word)):
little_word = word[index_]
if little_word.isdigit():
emoji_name = emoji_num_name[int(little_word)]
emoji = emoji_dict[emoji_name]
word[index_] = emoji
text[index] = "".join(word)
text = "".join(text)
text = text.encode('utf-16', 'surrogatepass').decode('utf-16')
print(text)
root = Tk()
root.tk.call('encoding', 'system', 'utf-8')
root.configure(width=500, height=500)
font = "Courier"
customFont = tkFont.Font(family=font, size=14)
emoji_frame = LabelFrame(text="emojis")
emoji_frame.place(x=10, y=60)
search_var = StringVar()
search_entry = Entry(root, textvariable=search_var)
search_entry.place(x=10, y=10)
search_button = Button(root, text="search", command=lambda: search(search_var.get().upper()))
search_button.place(x=10, y=30)
displat_all_button = Button(root, text="display all", command=lambda: creates_emojis())
displat_all_button.place(x=60, y=30)
sumbit_var = StringVar()
sumbit_entry = Entry(root, textvariable=sumbit_var)
sumbit_entry.place(x=200, y=10)
sumbit_button = Button(root, text="sumbit", command=lambda: sumbit(sumbit_var.get()))
sumbit_button.place(x=200, y=30)
creates_emojis()
root.mainloop()
This is a runnable example of what i made, I've created a kind of table where you can insert as many emojis as you want (by editing the emoji_dict and inserting the emoji that you want) and return an output in utf-8.
For find the emoji surrogate pair i've used the code
import re
_nonbmp = re.compile(r'[\U00010000-\U0010FFFF]')
def _surrogatepair(match):
char = match.group()
assert ord(char) > 0xffff
encoded = char.encode('utf-16-le')
return (
chr(int.from_bytes(encoded[:2], 'little')) +
chr(int.from_bytes(encoded[2:], 'little')))
def with_surrogates(text):
return _nonbmp.sub(_surrogatepair, text)
emoji_dict = {
"Grinning_Face": u'\ud83d\ude00',
"Grinning_Face_With_Big_Eyes": u'\ud83d\ude03',
"Grinning_Face_With_Smiling_Eyes": u'\ud83d\ude04',
"Beaming_Face_With_Smiling_Eyes": u'\ud83d\ude01',
"Grinning_Squinting_Face": u'\ud83d\ude06',
"Grinning_Face_With_Sweat": u'\ud83d\ude05',
"Laughing_on_the_Floor": u'\ud83e\udd23',
"Tears_of_Joy": u'\ud83d\ude02',
"Smiling_Face_Slightly": u'\ud83d\ude42',
"Upside-Down_Face": u'\ud83d\ude43',
"Winking_Face": u'\ud83d\ude09',
}
emoji_list =[ "😀", "😃", "😄", "😁", "😆", "😅", "🤣", "😂", "🙂", "🙃", "😉", ]
for emoji in emoji_list:
print(repr(_nonbmp.sub(_surrogatepair, emoji)))
you can found it at this question
Python: Find equivalent surrogate pair from non-BMP unicode char