I've been trying to make a simple text pad with syntax highlighting for python. but the problem is when i open quote a string ad pt the closing quote, the text are the quotes doesn't change back, here's how it looks:
here is my current code:
from tkinter import * # All from Tkinter
# =============================================================================
class vwin():
def __init__(self,args,master=None):
if type(args[3]) == type(self):
self.window = Toplevel(args[3].window)
elif args[3].lower() == 'tk':
self.window = Tk()
self.window.title(args[0])
self.window.geometry(args[1])
self.window.state(args[2])
def mainloop():
self.window.mainloop()
class customtext:
def __init__(self,master):
import tkinter.scrolledtext as scrolltxt
self.textarea = scrolltxt.ScrolledText(master)
self.textarea.configure(bg = "#555555",
insertbackground = "#dddddd",
font = "Courier 14 bold",
tabs = 40,
foreground="#dddddd")
self.textarea.pack(fill = BOTH, expand = True)
# TAGS ----------------------------------------------------------------
self.textarea.tag_configure("Token.Comment",
foreground="#00ff00")
self.textarea.tag_configure("Token.Literal.String",
foreground="#ff99cc")
self.textarea.tag_configure("Token.Keyword",
foreground="#aaaa00")
self.textarea.tag_configure("Token.Name.Function",
foreground="#ffff00")
def highlight(self,event=None):
# Imports PythonLex from Pygments -----
from pygments import lex
from pygments.lexers import PythonLexer
# Content Search ------------------------------------------------------
self.textarea.mark_set("range_start", "1.0")
data = self.textarea.get("1.0", "end-1c")
for token, content in lex(data, PythonLexer()):
self.textarea.mark_set("range_end",
"range_start + %dc" % len(content))
self.textarea.tag_add(str(token), "range_start", "range_end")
self.textarea.mark_set("range_start", "range_end")
def stat_title(self,event=None):
ind = self.textarea.index(INSERT)
root.window.title('VenomPad Mini' + "[Index:" + str(ind) + "]")
def select_all(self,event):
self.textarea.tag_add(SEL, "1.0", END)
self.textarea.mark_set(INSERT, "1.0")
self.textarea.see(INSERT)
# =============================================================================
# :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
root = vwin(['VenomPad Mini','640x480-25-25','normal','Tk'])
text = customtext(root.window)
root.window.bind("<Key>", text.highlight)
root.window.bind("<KeyRelease>", text.stat_title)
root.window.bind("<Control-Key-a>", text.select_all)
root.window.mainloop()
# :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
Tagging a range inside another range, doesn't shorten the range.
The simplest thing I could think of would be to remove the existing tags before adding the tags:
def highlight(self,event=None):
...
data = self.textarea.get("1.0", "end-1c")
# Remove the existing tags from textarea
for tag in self.textarea.tag_names():
self.textarea.tag_remove(tag, "1.0", "end")
for token, content in lex(data, PythonLexer()):
self.textarea.mark_set("range_end",
"range_start + %dc" % len(content))
self.textarea.tag_add(str(token), "range_start", "range_end")
self.textarea.mark_set("range_start", "range_end")
...
Related
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'm getting the error "UnboundLocalError: local variable 'qn' referenced before assignment" on running the code. Why is that? How can I correct it? I'm new to tkinter so please try to keep it simple. This is part of the code for a game I was writing. It would be a great help if I could get an answer soon
from tkinter import *
from tkinter import messagebox
from io import StringIO
root = Tk()
root.title("Captain!")
root.geometry("660x560")
qn = '''1$who are you?$char1$i am joe$3$i am ben$2
2$what are you?$char2$i am a person$1$i am nobody$3
3$how are you?$char3$i am fine$2$i'm alright$1'''
var = '''1$10$-35$20$15$-20
2$9$7$30$-5$-15
3$10$-25$-15$10$5'''
class Game :
def __init__(self):
self.m_cur = {1:["Military",50]}
self.c_cur = {1:["People's",50]}
self.r_cur = {1:["Research",50]}
self.i_cur = {1:["Industrial",50]}
self.p_cur = {1:["Research",50]}
#function to clear all widgets on screen when called
def clear(self):
for widget in root.winfo_children():
widget.destroy()
#function to quit the window
def exit(self):
msg = messagebox.askquestion("Thank you for playing","Are you sure you want to exit?")
if msg == "yes" :
root.destroy()
else:
Game.main(self)
#start function
def start(self):
Label(root,text="Hello, what should we call you?",font=("segoe print",20)).grid(row=0,column=0)
name = Entry(root,width=20)
name.grid(row=1,column=0)
Button(root,text="Enter",font=("segoe print",20),command=lambda: Game.main(self)).grid(row=1,column=1)
self.name=name.get()
#main function
def main(self):
Game.clear(self)
Label(root,text="Welcome to the game",font=("segoe print",20)).grid(row=0,column=0)
Label(root,text='What do you want to do?',font=("segoe print",20)).grid(row=1,column=0)
Button(root,text="Start Game",font=("segoe print",20),command=lambda: Game.qn_func(self,1)).grid(row=2,column=0)
Button(root,text="Exit Game",font=("segoe print",20),command=lambda: Game.exit(self)).grid(row=3,column=0)
#function to check variables and display game over
def game_over(self,x_cur):
if x_cur[1][1]<=0 or x_cur[1][1]>=100 : #condition to check game over
Game.clear(self)
Label(root,text=x_cur)
Label(root,text="GAME OVER",font=("ariel",20)).place(relx=0.5,rely=0.5,anchor=CENTER)
Button(root,text="Continue",font=("segoe print",20),command=lambda: Game.main(self)).place(relx=0.5,rely=0.6)
#function to display question and variables
def qn_func(self,qn_num) :
Game.clear(self)
#accessing the questions
q_file = StringIO(qn)
#reading the question, options, next qn numbers and the character name from the file
qn_list = q_file.readlines()
qn = qn_list[qn_num-1].strip().split("$")[1]
char_name = qn_list[qn_num-1].strip().split("$")[2]
qn1 = qn_list[qn_num-1].strip().split("$")[3]
qn2 = qn_list[qn_num-1].strip().split("$")[5]
n_qn1 = int(qn_list[qn_num-1].strip().split("$")[4])
n_qn2 = int(qn_list[qn_num-1].strip().split("$")[6])
#displaying the character name and the question as a label frame widget with character name as parent
label_frame = LabelFrame(root,text = char_name,font = ("segoe print",20))
label = Label(label_frame,text = qn,font = ("segoe print",20))
label_frame.place(relx=0.5,rely=0.5,anchor=CENTER)
label.pack()
q_file.close()
#accessing variables
v_file = StringIO(var)
#reading values of variables from file
v_list = v_file.readlines()
self.r_cur[1][1] += int(v_list[qn_num-1].strip().split("$")[1])
self.c_cur[1][1] += int(v_list[qn_num-1].strip().split("$")[2])
self.i_cur[1][1] += int(v_list[qn_num-1].strip().split("$")[3])
self.m_cur[1][1] += int(v_list[qn_num-1].strip().split("$")[4])
self.p_cur[1][1] += int(v_list[qn_num-1].strip().split("$")[5])
#running each variable through game_over to see if you are dead
Game.game_over(self,self.r_cur)
Game.game_over(self,self.c_cur)
Game.game_over(self,self.i_cur)
Game.game_over(self,self.m_cur)
Game.game_over(self,self.p_cur)
#defining the Doublevar variables
s_var1 = DoubleVar()
s_var2 = DoubleVar()
s_var3 = DoubleVar()
s_var4 = DoubleVar()
s_var5 = DoubleVar()
#setting the values in the scales
s_var1.set(self.r_cur[1][1])
s_var2.set(self.c_cur[1][1])
s_var3.set(self.i_cur[1][1])
s_var4.set(self.m_cur[1][1])
s_var5.set(self.p_cur[1][1])
#variables as scale widgets
scale1 = Scale(root,from_=100,to=0,orient=VERTICAL,sliderlength=10,variable=s_var1)
scale2 = Scale(root,from_=100,to=0,orient=VERTICAL,sliderlength=10,variable=s_var2)
scale3 = Scale(root,from_=100,to=0,orient=VERTICAL,sliderlength=10,variable=s_var3)
scale4 = Scale(root,from_=100,to=0,orient=VERTICAL,sliderlength=10,variable=s_var4)
scale5 = Scale(root,from_=100,to=0,orient=VERTICAL,sliderlength=10,variable=s_var5)
#displaying the scale widgets on the screen
scale1.grid(row=0,column=0)
scale2.grid(row=0,column=1)
scale3.grid(row=0,column=2)
scale4.grid(row=0,column=3)
scale5.grid(row=0,column=4)
#disabling the scales
scale1.config(state=DISABLED)
scale2.config(state=DISABLED)
scale3.config(state=DISABLED)
scale4.config(state=DISABLED)
scale5.config(state=DISABLED)
v_file.close()
#displaying the buttons on the screen
Button(root,text=qn1,command=lambda: Game.qn_func(self,n_qn1)).place(relx=0.2,rely=0.7,anchor=W,width=200,height=50)
Button(root,text=qn2,command=lambda: Game.qn_func(self,n_qn2)).place(relx=0.8,rely=0.7,anchor=E,width=200,height=50)
game = Game()
game.start()
root.mainloop()
You can see in this particular section that you have called on 'qn' before it was even defined:
#function to display question and variables
def qn_func(self,qn_num) :
Game.clear(self)
#accessing the questions
q_file = StringIO(qn)
#reading the question, options, next qn numbers and the character name from the file
qn_list = q_file.readlines()
qn = qn_list[qn_num-1].strip().split("$")[1]
The variable needs to be assigned a value before being used. Here, you call q_file = StringIO(qn) before you have defined qn = qn_list....
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
I have a Excel as Below
|---------------------|------------------|
| Heading 1 | Heading 2 |
|---------------------|------------------|
| Row1 | Value 1 |
|---------------------|------------------|
| Row2 | Value 2 |
|---------------------|------------------|
I am reading from excel and Showing the Values of Heading 1 in the GUI
When I click on submit Button , I need to read the value/text of the CheckBox depending on the selection of the CheckBox and Create XML by using Excel for only selected values
Problem is How can I only select the values in the Excel , depending on the selection of check Box. (But I know how to identify which check box is checked ). But how to relate to Excel is I am facing problem
Note: I Know how to create XML from excel
I know how to identify when submit is clicked
GUI Code:
Config.Py
import tkinter as tk
import xlrd
import GetValueFromExcel
from GetValueFromExcel import ExcelValue
from array import array
from tkinter import *
from tkinter import ttk, Button
from tkinter import *
root = Tk()
class UICreation():
def __init__(self):
print ("I m in __init__")
self.tabControl = ttk.Notebook(root)
self.tab1 = ttk.Frame(self.tabControl)
self.tab2 = ttk.Frame(self.tabControl)
def tabcreation(self):
print ("I M in Tab Creation")
self.tabControl.add(self.tab1 , text="Tab1")
#self.tabControl(self.tab1, text= t)
##self.tabControl(self.tab1, )
self.tabControl.add(self.tab2, text="Tab2")
self.tabControl.grid()
def checkbox(self):
print ("I M in checkBox")
checkBox1 = Checkbutton(self.tab1, text=str(t[0]))
checkBox2 = Checkbutton(self.tab1, text=str(t[1]))
Checkbutton()
checkBox1.grid()
checkBox2.grid()
def button(self):
button = Button(self.tab1 , text="Submit", command=self.OnButtonClick)
button.grid()
def OnButtonClick(self):
print ("I am Working")
if __name__ == '__main__':
ui = UICreation()
ev = GetValueFromExcel.ExcelValue()
ev.readExcelValue()
t = ev.readExcelValue()
print(t)
ui.tabcreation()
ui.checkbox()
ui.button()
#ev = readExcelValue()
root.mainloop()
GetValueFromExcel.py
import xlrd
class ExcelValue():
def __init__(self):
self.wb=xlrd.open_workbook(r"C:\<FilePath>\Filename.xlsx")
#self.ws=self.wb.sheet_by_name("Sheet1")
for sheet in self.wb.sheets():
self.number_of_rows = sheet.nrows
self.number_of_columns = sheet.ncols
def readExcelValue(self):
result_data = []
row_data = []
for sheet in self.wb.sheets():
for curr_row in range(1, self.number_of_rows, 1):
#for curr_col in range(0, self.number_of_columns , 1):
#data = sheet.cell_value(curr_row, curr_col) # Read the data in the current cell
data = sheet.cell_value(curr_row, 0)
#print(data)
row_data.append(data)
result_data.append(row_data)
return result_data[1]
You can pass the value to Checkbutton like this:
def checkbox(self):
print ("I M in checkBox")
checkBox1 = Checkbutton(self.tab1, text=str(t.keys()[0]), variable=t.values()[0])
checkBox2 = Checkbutton(self.tab1, text=str(t.keys()[1]), variable=t.values()[1])
Checkbutton()
checkBox1.grid()
checkBox2.grid()
and you must change readExcelValue, like below:
def readExcelValue(self):
result_data = {}
for sheet in self.wb.sheets():
for curr_row in range(1, self.number_of_rows, 1):
data = sheet.cell_value(curr_row, 0)
value = sheet.cell_value(curr_row, 1)
result_data[data] = value
return result_data
I am trying to add UserControl to a WinForm using PythonNet but not having any luck. For testing, I added a button and that shows up but not the UserControl and I am not sure what I a doing wrong.
All the code can be placed into one py file. I broke into a few sections hoping it will be easier to read.
USER CONTROL
class Field(WinForms.UserControl):
def __init__(self):
self.InitializeComponents()
pass
def InitializeComponents(self):
self.components = System.ComponentModel.Container()
self.label = WinForms.Label()
self.textBox = WinForms.Label()
## Label
# self.label.Anchor = ((WinForms.AnchorStyles)(
# ((WinForms.AnchorStyles.Top | WinForms.AnchorStyles.Bottom)
# | WinForms.AnchorStyles.Left)))
self.label.AutoSize = True
self.label.Location = System.Drawing.Point(3, 7)
self.label.Name = "label"
self.label.Size = System.Drawing.Size(29, 13)
self.label.TabIndex = 0
self.label.Text = "label"
## TextBox
# self.textBox.Anchor = ((WinForms.AnchorStyles)(
# (((WinForms.AnchorStyles.Top | WinForms.AnchorStyles.Bottom)
# | WinForms.AnchorStyles.Left)
# | WinForms.AnchorStyles.Right)))
# self.textBox.Location = System.Drawing.Point(115, 3)
self.textBox.Name = "textBox"
self.textBox.Size = System.Drawing.Size(260, 20)
self.textBox.TabIndex = 1
## Control
self.AutoScaleMode = WinForms.AutoScaleMode.Font
self.Controls.Add(self.textBox)
self.Controls.Add(self.label)
self.Name = "Field"
self.Size = System.Drawing.Size(378, 26)
# self.PerformLayout()
PARENT FORM
class ParentForm(WinForms.Form):
def __init__(self):
self.InitializeComponents()
# region Form Design
def InitializeComponents(self):
self.components = System.ComponentModel.Container()
self.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
self.ClientSize = System.Drawing.Size(385, 180)
self.Name = "ParentForm"
self.Text = "Parent Form"
self.field1 = Field()
self.field1.Location = Point(13, 13)
self.field1.Name = "field1"
self.field1.Size = Size(378, 26)
self.field1.TabIndex = 1
self.Controls.Add(self.field1)
self.button1 = WinForms.Button()
self.button1.Location = Point(13, 50)
self.button1.Size = Size(50, 20)
self.button1.Text = "Button1"
self.Controls.Add(self.button1)
pass
def Dispose(self):
self.components.Dispose()
WinForms.Form.Dispose(self)
ENTRY POINT AND IMPORTS
import clr
import System
import System.Windows.Forms as WinForms
from System.IO import File
from System.Text import Encoding
from System.Drawing import Color, Point, Size
from System.Threading import ApartmentState, Thread, ThreadStart
def appThread():
app = ParentForm()
WinForms.Application.Run(app)
app.Dispose()
def appEntry():
thread = Thread(ThreadStart(appThread))
thread.SetApartmentState(ApartmentState.STA)
thread.Start()
thread.Join()
if __name__ == '__main__':
appEntry()