I am trying to send selected values from radiobuttons into a .docx file
importing what I need, focus is on docx
import tkinter as tk
from docx import Document
main = tk.Tk()
these are my options that I need to place into a word document on the left of the table, they act as questions in a survey.
info = ["option 1", "option 2", "option 3", "option 4"
]
Here I am placing radiobuttons called Yes, No & N/A which are answers to the options on the left(list of info above) and also Label to represent options or in other words questions..
vars = []
for idx,i in enumerate(info):
var = tk.IntVar(value=0)
vars.append(var)
lblOption = tk.Label(main,text=i)
btnYes = tk.Radiobutton(main, text="Yes", variable=var, value=2)
btnNo = tk.Radiobutton(main, text="No", variable=var, value=1)
btnNa = tk.Radiobutton(main, text="N/A", variable=var,value=0)
lblOption.grid(column=0,row=idx)
btnYes.grid(column=1,row=idx)
btnNo.grid(column=2,row=idx)
btnNa.grid(column=3,row=idx)
Here is my function, creating a document and saving is the easy part. My issue is that I am muddled up creating a table that will have; Options on the left (from info) at the top are the headers (see RadioButtons yes, no, & N/a). And selected data, as an example, if for option 1 I have selected No, then save the data into a .docx file with the one been selected (See example bottom of page at Desired output).
def send():
document = Document()
section = document.sections[0]
#add table
table = document.add_table(1, 4)
#style table
table.style = 'Table Grid'
#table data retrived from Radiobuttons
items = vars.get()
#populate header row
heading_cells = table.rows[0].cells
heading_cells[0].text = "Options"
heading_cells[1].text = btnYes.cget("text")
heading_cells[2].text = btnNo.cget("text")
heading_cells[3].text = btnNa.cget("text")
for item in items:
cells = table.add_row().cells
cells[0].text = #Options
cells[1].text = #Yes values
cells[2].text = #No values
cells[3].text = #N/A values
#save doc
document.save("test.docx")
#button to send data to docx file
btn = tk.Button(main, text="Send to File", command= send)
btn.grid()
main.mainloop()
this is what it opens up:
Here is the desired output:
Number 1 represents selected items from the tkinter application. But will figure out how to change it to a tick box.
I am kinda confused where I am at, I am new using docx.. been trying to read the documentation.. and this is where I digged my self a hole into.
In your current code, vars is a list of IntVars. You want to get each value individually instead of vars.get(). Also when writing to docx file, you need both info and values of radiobuttons, to track them both you can use an index.
With minimal changes to your code, you can use something like this.
def send():
...
...
heading_cells[3].text = btnNa.cget("text")
for idx, item in enumerate(vars):
cells = table.add_row().cells
cells[0].text = info[idx] # gets the option name
val = item.get() #radiobutton value
if val == 2: # checks if yes
cells[1].text = "1"
elif val == 1: # checks if no
cells[2].text = "1"
elif val == 0: # checks if N/A
cells[3].text = "1"
#save doc
document.save("test.docx")
or you can use a dictionary to map radiobuttons to cells.
valuesCells = {0: 3, 1: 2, 2: 1} # value of radiobutton: cell to write
# hard to read what's going on though
for idx, item in enumerate(vars):
cells = table.add_row().cells
cells[0].text = info[idx] # gets the option name
val = item.get()
cells[valuesCells[val]].text = "1"
#save doc
document.save("test.docx")
Related
def kayit_ekle_update(): ##
kayit_listesiVar.set('') # remove default selection only, not the full list
kayit_listesiOM['menu'].delete(0, 'end') # remove full list
kayitlilarOM = os.listdir("allin1/data_records")
for opt in kayitlilarOM:
kayit_listesiOM['menu'].add_command(label=opt, command=tk._setit(kayit_listesiVar, opt))
kayit_listesiVar.set(kayitlilarOM[0]) # default value set
def entri_doldur(se):
## get data from excel and append them to a new list(veri_al_list)
veri_al_list = []
om_deger = "allin1/data_records/" + kayit_listesiVar.get()
wb_kayit = load_workbook(om_deger)
ws_kayit = wb_kayit.active
for column_data in ws_kayit['1']:
veri_al_list.append(column_data.value)
veri_al_list = [' ' if v is None else v for v in veri_al_list] # None elemanı hata verdiriyor. Burada tüm None olanları "" ile değiştiriyoruz.
print(veri_al_list)
## There are Entry widgets created with for loop.
## en in entry_liste ==> Entries
## ne in veri_al_liste ==> data list from excel
for en, ne in zip(entry_liste, veri_al_list):
en.delete(0,END)
en.insert(END, ne)
wb_kayit.close()
kayitlilarOM = os.listdir("allin1/data_records")
kayit_listesiVar = StringVar()
kayit_listesiVar.set("Kayıt seç")
kayit_listesiOM = OptionMenu(ust, kayit_listesiVar, *kayitlilarOM, command=entri_doldur)
I have entry widgets in my code. The user can enter data and save them. Each time this data is saved, a new excel file is created and the data is saved in it.
The name of each saved excel file is displayed in an optionmenu. When we select a record from the Optionmenu, the entri_doldur() function works and the entries are filled according to the record.
I can delete the selected record with the button. When deleted, both the entries are empty and the option menu is updated.
But the problem occurs when I create a new record. Creating a new excel file. The data is saved in it. Option menu is being updated. But after that, when I select a record in the optionmenu, the entri_doldur() function does not work. The information of the selected record does not fill the entries.
I am working on Dynamo for Revit. My code takes sheet numbers and other info, then creates labels and buttons for each IN element with a for loop. The GUI works fine and I have all the elements in place, but how do I tell each individual button to open a different sheet? See screenshot.
I need to understand the workflow, but here is the code of the loop if it helps:
# Create labels and buttons in loop
y = 50
a = 0
for i in res:
# creates section name label
text = str(res[a][0])
text = text[19:]
text = text[:-1]
labelSectionName = Label(Text = text)
labelSectionName.Parent = self
labelSectionName.Location = Point(gridColSecName,y)
labelSectionName.Width = gridWidthSecName
#labelSectionName.Height = 20
# creates sheet number label
text = str(res[a][2])
labelSectionName = Label(Text = text)
labelSectionName.Parent = self
labelSectionName.Location = Point(gridColSheetNum,y)
labelSectionName.Width = 50
# create button for opening sheet
button = Button()
button.Parent = self
button.Text = "Open Sheet"
button.Location = Point(gridColButtSheet,y)
# Register button event
button.Click += self.?????????????????????????????????????
and this is the code for opening the sheet taken from another script
sheet = UnwrapElement(IN[0])
sheet_action=(IN[1])
output = []
if (str(sheet_action) == "Yes"):
uidoc.RequestViewChange(sheet)
output.append("ActiveView set to: " + sheet.Name)
else:
pass
OUT = sheet_action
How do I make it so that I get all the items inside a listbox into a variable? I only manage to get the last item only. I want to print the items of a listbox into a new window but I only print the last item only.
get_content = listbox2.get(0, END)
bb = Label(receipt_window, text = "Pizzeria")
line1 = Label(receipt_window, text = "----------------------------------------------------------------")
for con_item in get_content:
con = (con_item.split('PHP'))
con1 = con[0]
con2 = con[1]
rec_content = f'{con1:<40}costs PHP{con2:<8}'
receipt = Label(receipt_window, text = rec_content)
bb.pack()
line1.pack()
receipt.pack()
The listbox contains:
The result:
It is because you use same variable receipt for the labels created inside the for loop and call receipt.pack() outside the for loop, so the last label created inside for loop will be packed only.
You need to call receipt.pack() inside the for loop:
get_content = listbox2.get(0, END)
bb = Label(receipt_window, text='Pizzeria')
line1 = Label(receipt_window, text='----------------------------------------------------------------')
bb.pack()
line1.pack()
for con_item in get_content:
con1, con2 = con_item.split('PHP')
rec_content = f'{con1:<40}costs PHP{con2:<8}'
receipt = Label(receipt_window, text=rec_content)
receipt.pack()
Note that it is better to use fixed width (monospaced) font for the labels.
I am devoloping an app where the user upload his excel file and gets the Sheets and columns. How do I get the Columns drop-down menu (The second one) to update with the Sheets drop-down menu(First one).
I have already tried to make a function 'Update' that gets the new sheet form the Fuction 'GetSheet' and update it. But it does not work as the column drop-down menu get Always stucked in the Default sheet.
master.title('ATT Analytics App')
master.geometry("400x250")
Myfile= filedialog.askopenfile()
wb = load_workbook(filename = str(Myfile.name))
#Sheets = wb.sheetnames
variable = StringVar(master)
variable.set(str(wb.sheetnames[2])) # default value
w = OptionMenu(master, variable, str(wb.sheetnames[0]), str(wb.sheetnames[1]), str(wb.sheetnames[2]), str(wb.sheetnames[3]))
w.pack()
def GetSheet():
FileRead = pd.read_excel(str(Myfile.name),sheet_name= str(variable.get()))
MyHeadres = list(FileRead.columns.values)
return MyHeadres, FileRead
variable1 = StringVar(master)
def Update(TheHeaders):
variable1.set(str(TheHeaders[0]))
wc = OptionMenu(master, variable1, str(TheHeaders[0]), str(TheHeaders[1]), str(TheHeaders[2]), str(TheHeaders[3]), str(TheHeaders[4]), str(TheHeaders[5]))
return wc
def RunAll():
GetMySheet, FileRead = GetSheet()
UpdateMysheet = Update(GetMySheet)
return UpdateMysheet, variable1.get(), FileRead
button = Button(master, text="Run", command=RunAll)
button.pack(side = TOP)
UpdateMysheet, MyColumn, ReadMyFile = RunAll()
UpdateMysheet.pack()
FileRead = ReadMyFile
mainloop()
I want to bring my Code to be able to update the Column Drop-down (Variable1) menu with the drop down menu (Variable), which works fine and also get to store the column you want and move on the choose another one and so on..
I would appreciate your help a lot.
Edit: Now when I choose another sheet, the Default value of the columns updates to the new sheet, but when I look the complete List, I find out that the values are from the old sheet.
I have a dropdown menu that shows soms posssible 'cycles'. These are actually .csv files containing some data. Then I have another dropdown that should show all the variables in this .csv file. So this second dropdown should update according to the file selected in the first dropdown. I found a similar
question and tried to implement this, but it did not work. The second dropdown remains empty. Note that I use pyspark to read the .csv files.
Cycles is a tuple containing all the .csv files in my working directory.
scW1 = widgets.Dropdown(description = 'Select file',options = cycles)
scW2 = widgets.Dropdown(description = 'Select variable')
def plotvar(sender):
df=sc.textFile(str(scW1.value)).map(lambda x: x.split(','))
header = tuple(df.first())
print(header)
with scW2.hold_trait_notifications():
scW2.options = header
display(scW1)
display(scW2)
What goes wrong?
Lol 4 years, but I've been looking for this...
from IPython.display import display
from ipywidgets import Dropdown
def dropdown_eventhandler(change):
determine(dropdown.value)
# print(change.new)
option_list = (1, 2)
dep_1 = (1, 1)
dep_2 = (2, 2)
def determine(x):
if x == 1:
dropdown_dep.options = dep_1
else:
dropdown_dep.options = dep_2
dropdown = Dropdown(description="Choose one:", options=option_list)
dropdown_dep = Dropdown(description="Choose one:")
dropdown.observe(dropdown_eventhandler, names='value')
display(dropdown, dropdown_dep)