-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathid_generator_modern.py
More file actions
722 lines (626 loc) · 30.3 KB
/
Copy pathid_generator_modern.py
File metadata and controls
722 lines (626 loc) · 30.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
import tkinter as tk
from tkinter import ttk, messagebox
import uuid
import random
import string
import time
import hashlib
import subprocess
# 生成各种ID的函数
def generate_uuid_v1():
return str(uuid.uuid1())
def generate_uuid_v3(namespace, name):
try:
ns = uuid.UUID(namespace)
return str(uuid.uuid3(ns, name))
except:
return ""
def generate_uuid_v4():
return str(uuid.uuid4())
def generate_uuid_v5(namespace, name):
try:
ns = uuid.UUID(namespace)
return str(uuid.uuid5(ns, name))
except:
return ""
def generate_uuid_v6():
uuid1 = uuid.uuid1()
hex_str = uuid1.hex
v6_hex = hex_str[12:16] + hex_str[8:12] + hex_str[0:8] + hex_str[16:]
return f"{v6_hex[:8]}-{v6_hex[8:12]}-{v6_hex[12:16]}-{v6_hex[16:20]}-{v6_hex[20:]}"
def generate_uuid_v7():
timestamp = int(time.time() * 1000)
timestamp_hex = f"{timestamp:012x}"
random_part = ''.join(random.choices(string.hexdigits, k=10)).lower()
v7_hex = timestamp_hex + random_part
return f"{v7_hex[:8]}-{v7_hex[8:12]}-{v7_hex[12:16]}-{v7_hex[16:20]}-{v7_hex[20:]}"
def generate_short_uuid():
uuid_str = uuid.uuid4().hex
return hashlib.md5(uuid_str.encode()).hexdigest()[:8]
def generate_nil_uuid():
return "00000000-0000-0000-0000-000000000000"
def generate_max_uuid():
return "ffffffff-ffff-ffff-ffff-ffffffffffff"
def generate_nano_id(length=21):
alphabet = "_-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
return ''.join(random.choices(alphabet, k=length))
def generate_ulid():
timestamp = int(time.time() * 1000)
timestamp_str = f"{timestamp:012x}"
random_str = ''.join(random.choices(string.hexdigits, k=16)).lower()
return timestamp_str + random_str
def generate_cuid():
timestamp = int(time.time() * 1000)
counter = random.randint(0, 1000)
random_str = ''.join(random.choices(string.ascii_lowercase + string.digits, k=10))
return f"c{timestamp}{counter}{random_str}"
def generate_cuid2():
timestamp = int(time.time() * 1000)
random_str = ''.join(random.choices(string.ascii_lowercase + string.digits, k=16))
return f"{timestamp}{random_str}"
def generate_nuid():
return ''.join(random.choices(string.ascii_uppercase + string.digits, k=12))
def generate_snowflake():
timestamp = int(time.time() * 1000)
worker_id = 1
process_id = 1
sequence = random.randint(0, 4095)
return f"{timestamp}{worker_id:02d}{process_id:02d}{sequence:04d}"
def generate_sonyflake():
timestamp = int(time.time() * 1000)
machine_id = 1
sequence = random.randint(0, 1023)
return f"{timestamp}{machine_id:02d}{sequence:03d}"
def generate_upid(prefix="zzzz"):
timestamp = int(time.time() * 1000)
random_str = ''.join(random.choices(string.ascii_lowercase + string.digits, k=10))
return f"{prefix}{timestamp}{random_str}"
def generate_tsid():
timestamp = int(time.time() * 1000)
random_str = ''.join(random.choices(string.ascii_lowercase + string.digits, k=10))
return f"{timestamp}{random_str}"
def generate_object_id():
timestamp = int(time.time())
machine_id = random.randint(0, 16777215)
process_id = random.randint(0, 65535)
counter = random.randint(0, 16777215)
return f"{timestamp:08x}{machine_id:06x}{process_id:04x}{counter:06x}"
def generate_scru128():
timestamp = int(time.time() * 1000)
random_str = ''.join(random.choices(string.ascii_lowercase + string.digits, k=20))
return f"{timestamp}{random_str}"
def generate_hardware_uuid():
try:
result = subprocess.run(
["wmic", "csproduct", "get", "uuid", "/value"],
capture_output=True,
text=True,
check=True
)
for line in result.stdout.strip().split('\n'):
line = line.strip()
if line.startswith('UUID='):
return line.split('=', 1)[1].strip()
result = subprocess.run(
["wmic", "csproduct", "get", "uuid"],
capture_output=True,
text=True,
check=True
)
lines = result.stdout.strip().split('\n')
if len(lines) >= 2:
all_text = ''.join(line.strip() for line in lines[1:])
if len(all_text) >= 36:
return all_text[:36]
return ""
except Exception as e:
print(f"获取硬件UUID失败: {e}")
return ""
# 主应用类
class IDGeneratorApp:
def __init__(self, root):
self.root = root
self.root.title("ID生成器")
self.root.geometry("600x550")
self.root.resizable(False, False)
# 主题配置
self.setup_modern_theme()
# ID类型列表 - 通俗易懂的中文名称
self.id_types = [
"uuidv1", "uuidv3", "uuidv4", "uuidv5", "uuidv6", "uuidv7",
"shortuuid", "niluuid", "maxuuid", "nanoid", "ulid",
"cuid", "cuid2", "nuid", "snowflake", "sonyflake",
"upid", "tsid", "objectid", "scru128", "hardwareuuid"
]
self.id_type_names = {
"uuidv1": "UUID v1(基于时间)",
"uuidv3": "UUID v3(基于MD5名称)",
"uuidv4": "UUID v4(随机)",
"uuidv5": "UUID v5(基于SHA-1名称)",
"uuidv6": "UUID v6(重新排序时间)",
"uuidv7": "UUID v7(基于Unix时间)",
"shortuuid": "短UUID",
"niluuid": "空UUID",
"maxuuid": "最大UUID",
"nanoid": "Nano ID(短随机ID)",
"ulid": "ULID(时间有序ID)",
"cuid": "CUID(内容寻址ID)",
"cuid2": "CUID2(新一代内容寻址ID)",
"nuid": "NUID(快速唯一ID)",
"snowflake": "雪花ID(分布式ID)",
"sonyflake": "索尼雪花ID",
"upid": "UPID(可排序唯一ID)",
"tsid": "TSID(时间排序ID)",
"objectid": "MongoDB对象ID",
"scru128": "SCRU128(连续唯一ID)",
"hardwareuuid": "硬件UUID(设备唯一标识)"
}
# 预设UUIDs
self.predefined_uuids = {
"DNS": "6ba7b810-9dad-11d1-80b4-00c04fd430c8",
"URL": "6ba7b811-9dad-11d1-80b4-00c04fd430c8",
"OID": "6ba7b812-9dad-11d1-80b4-00c04fd430c8",
"X.500": "6ba7b814-9dad-11d1-80b4-00c04fd430c8"
}
# 语言支持 - 添加中英文翻译字典
self.language = "zh" # 默认中文
self.translations = {
"zh": {
"app_title": "UUID获取器",
"select_id_type": "选择ID类型",
"advanced_options": "高级选项",
"namespace": "命名空间",
"name": "名称",
"prefix": "前缀",
"generate_result": "生成结果",
"regenerate": "🔄 重新生成",
"copy": "📋 复制",
"random_uuid": "随机UUID",
"preset_uuid": "预设UUID",
"select_preset_uuid": "选择预设UUID",
"success_copy": "成功",
"success_copy_msg": "已成功复制到剪贴板!",
"error_copy": "错误",
"error_copy_msg": "没有可复制的内容",
"preset_uuid_title": "预设UUID值"
},
"en": {
"app_title": "UUID Generator",
"select_id_type": "Select ID Type",
"advanced_options": "Advanced Options",
"namespace": "Namespace",
"name": "Name",
"prefix": "Prefix",
"generate_result": "Generation Result",
"regenerate": "🔄 Regenerate",
"copy": "📋 Copy",
"random_uuid": "Random UUID",
"preset_uuid": "Preset UUID",
"select_preset_uuid": "Select Preset UUID",
"success_copy": "Success",
"success_copy_msg": "Successfully copied to clipboard!",
"error_copy": "Error",
"error_copy_msg": "No content to copy",
"preset_uuid_title": "Preset UUID Values"
}
}
# ID类型名称的中英文翻译
self.id_type_names_i18n = {
"zh": {
"uuidv1": "UUID v1(基于时间)",
"uuidv3": "UUID v3(基于MD5名称)",
"uuidv4": "UUID v4(随机)",
"uuidv5": "UUID v5(基于SHA-1名称)",
"uuidv6": "UUID v6(重新排序时间)",
"uuidv7": "UUID v7(基于Unix时间)",
"shortuuid": "短UUID",
"niluuid": "空UUID",
"maxuuid": "最大UUID",
"nanoid": "Nano ID(短随机ID)",
"ulid": "ULID(时间有序ID)",
"cuid": "CUID(内容寻址ID)",
"cuid2": "CUID2(新一代内容寻址ID)",
"nuid": "NUID(快速唯一ID)",
"snowflake": "雪花ID(分布式ID)",
"sonyflake": "索尼雪花ID",
"upid": "UPID(可排序唯一ID)",
"tsid": "TSID(时间排序ID)",
"objectid": "MongoDB对象ID",
"scru128": "SCRU128(连续唯一ID)",
"hardwareuuid": "硬件UUID(设备唯一标识)"
},
"en": {
"uuidv1": "UUID v1(Time-based)",
"uuidv3": "UUID v3(MD5-based)",
"uuidv4": "UUID v4(Random)",
"uuidv5": "UUID v5(SHA-1-based)",
"uuidv6": "UUID v6(Reordered Time)",
"uuidv7": "UUID v7(Unix Time)",
"shortuuid": "Short UUID",
"niluuid": "Nil UUID",
"maxuuid": "Max UUID",
"nanoid": "Nano ID(Short Random)",
"ulid": "ULID(Time Ordered)",
"cuid": "CUID(Content-addressed)",
"cuid2": "CUID2(Next-gen Content)",
"nuid": "NUID(Fast Unique)",
"snowflake": "Snowflake(Distributed)",
"sonyflake": "Sonyflake",
"upid": "UPID(Orderable Unique)",
"tsid": "TSID(Time Sorted)",
"objectid": "MongoDB ObjectID",
"scru128": "SCRU128(Continuous)",
"hardwareuuid": "Hardware UUID(Device ID)"
}
}
# 更新当前ID类型选项
self.id_type_names = self.id_type_names_i18n[self.language]
# 变量初始化 - 存储ID类型的键而不是显示值
self.current_id_type_key = tk.StringVar(value="uuidv4")
self.current_id_type = tk.StringVar(value=self.id_type_names["uuidv4"])
self.namespace = tk.StringVar(value="")
self.name = tk.StringVar(value="")
self.prefix = tk.StringVar(value="zzzz")
self.result = tk.StringVar(value="")
self.create_modern_widgets()
self.generate()
def setup_modern_theme(self):
# 定义和谐统一的主题颜色,消除色块感
self.colors = {
"bg": "#f0f2f5", # 柔和的背景色
"surface": "#ffffff",
"primary": "#4f46e5",
"primary_hover": "#4338ca",
"secondary": "#06b6d4",
"secondary_hover": "#0891b2",
"text": "#1e293b",
"text_secondary": "#64748b",
"border": "#e2e8f0",
"success": "#10b981",
"success_hover": "#059669",
}
# 设置主题样式
style = ttk.Style()
style.theme_use('clam')
# 配置主窗口背景
self.root.configure(background=self.colors['bg'])
# 配置所有TFrame样式 - 统一背景色
style.configure('Modern.TFrame',
background=self.colors['bg'])
# 配置所有TLabel样式 - 统一背景色
style.configure('Modern.TLabel',
background=self.colors['bg'],
foreground=self.colors['text'],
font=('Segoe UI', 10))
# 配置TButton样式 - 现代化按钮
style.configure('Modern.TButton',
background=self.colors['primary'],
foreground='white',
font=('Segoe UI', 11, 'bold'),
padding=12,
borderwidth=0,
relief='flat')
# 配置TButton悬停效果
style.map('Modern.TButton',
background=[('active', self.colors['primary_hover'])])
# 配置次要按钮样式
style.configure('Secondary.TButton',
background=self.colors['secondary'],
foreground='white',
font=('Segoe UI', 11, 'bold'),
padding=12,
borderwidth=0,
relief='flat')
style.map('Secondary.TButton',
background=[('active', self.colors['secondary_hover'])])
# 配置TEntry样式 - 现代化输入框
style.configure('Modern.TEntry',
background=self.colors['surface'],
foreground=self.colors['text'],
font=('Segoe UI', 10),
padding=10,
borderwidth=1,
relief='solid',
fieldbackground=self.colors['surface'])
# 配置完整的Combobox样式
style.configure('Modern.TCombobox',
background=self.colors['surface'],
foreground=self.colors['text'],
font=('Segoe UI', 10),
padding=10,
borderwidth=1,
relief='solid')
# 配置Combobox输入区域背景
style.configure('Modern.TCombobox', fieldbackground=self.colors['surface'])
# 配置Combobox下拉列表样式
style.configure('Modern.TCombobox.Listbox',
background=self.colors['surface'],
foreground=self.colors['text'],
font=('Segoe UI', 10))
# 配置Combobox箭头样式
style.configure('Modern.TCombobox.Arrow',
background=self.colors['primary'],
foreground='white')
# 确保所有组件都使用正确的背景色
style.configure('TLabel', background=self.colors['bg'], foreground=self.colors['text'])
style.configure('TLabelframe', background=self.colors['bg'], foreground=self.colors['text'])
style.configure('TLabelframe.Label', background=self.colors['bg'], foreground=self.colors['text'])
def create_modern_widgets(self):
# 主框架 - 垂直布局,统一背景色
main_frame = ttk.Frame(self.root, style='Modern.TFrame', padding="30")
main_frame.pack(fill=tk.BOTH, expand=True)
# 标题区域 - 包含标题和语言切换按钮
title_area = ttk.Frame(main_frame, style='Modern.TFrame')
title_area.pack(anchor=tk.CENTER, pady=(0, 30), fill=tk.X)
# 标题
self.title_label = ttk.Label(title_area, text=self.translations[self.language]["app_title"],
font=('Segoe UI', 24, 'bold'),
foreground=self.colors['primary'],
style='Modern.TLabel')
self.title_label.pack(side=tk.LEFT, anchor=tk.CENTER, expand=True)
# 语言切换按钮
self.lang_btn = ttk.Button(title_area,
text="EN" if self.language == "zh" else "中文",
command=self.toggle_language,
style='Secondary.TButton')
self.lang_btn.pack(side=tk.RIGHT, padx=(10, 0))
# ID类型选择 - 直接放在主框架中
self.select_id_type_label = ttk.Label(main_frame, text=self.translations[self.language]["select_id_type"],
font=('Segoe UI', 12, 'bold'),
foreground=self.colors['text'],
style='Modern.TLabel')
self.select_id_type_label.pack(anchor=tk.W, pady=(0, 10))
# 使用现代化的Combobox
self.id_type_combo = ttk.Combobox(main_frame,
textvariable=self.current_id_type,
values=list(self.id_type_names.values()),
style='Modern.TCombobox',
state='readonly')
self.id_type_combo.pack(fill=tk.X, pady=(0, 25))
self.id_type_combo.bind('<<ComboboxSelected>>', self.on_id_type_change)
# 高级选项区域 - 简化设计,直接放在主框架中
self.advanced_frame = ttk.Frame(main_frame, style='Modern.TFrame')
self.advanced_frame.pack(fill=tk.X, pady=(0, 25))
# 命名空间和名称(仅UUID v3/v5显示)
self.namespace_frame = ttk.Frame(self.advanced_frame, style='Modern.TFrame')
# 命名空间行
self.namespace_label = ttk.Label(self.namespace_frame, text=self.translations[self.language]["namespace"],
font=('Segoe UI', 11, 'bold'),
foreground=self.colors['text'],
style='Modern.TLabel')
self.namespace_label.pack(anchor=tk.W, pady=(0, 5))
namespace_input_frame = ttk.Frame(self.namespace_frame, style='Modern.TFrame')
namespace_input_frame.pack(fill=tk.X, pady=(0, 15))
namespace_entry = ttk.Entry(namespace_input_frame,
textvariable=self.namespace,
style='Modern.TEntry')
namespace_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 10))
# 随机UUID按钮
self.random_uuid_btn = ttk.Button(namespace_input_frame,
text=self.translations[self.language]["random_uuid"],
command=self.set_random_namespace,
style='Secondary.TButton')
self.random_uuid_btn.pack(side=tk.LEFT, padx=(0, 8))
# 预设UUID按钮
self.preset_uuid_btn = ttk.Button(namespace_input_frame,
text=self.translations[self.language]["preset_uuid"],
command=self.show_predefined_uuids,
style='Secondary.TButton')
self.preset_uuid_btn.pack(side=tk.LEFT)
# 名称行
self.name_label = ttk.Label(self.namespace_frame, text=self.translations[self.language]["name"],
font=('Segoe UI', 11, 'bold'),
foreground=self.colors['text'],
style='Modern.TLabel')
self.name_label.pack(anchor=tk.W, pady=(0, 5))
name_entry = ttk.Entry(self.namespace_frame,
textvariable=self.name,
style='Modern.TEntry')
name_entry.pack(fill=tk.X)
# 前缀区域(仅UPID显示)
self.prefix_frame = ttk.Frame(self.advanced_frame, style='Modern.TFrame')
self.prefix_label = ttk.Label(self.prefix_frame, text=self.translations[self.language]["prefix"],
font=('Segoe UI', 11, 'bold'),
foreground=self.colors['text'],
style='Modern.TLabel')
self.prefix_label.pack(anchor=tk.W, pady=(0, 5))
prefix_entry = ttk.Entry(self.prefix_frame,
textvariable=self.prefix,
style='Modern.TEntry')
prefix_entry.pack(fill=tk.X)
# 结果显示区域 - 简化设计
self.result_title_label = ttk.Label(main_frame, text=self.translations[self.language]["generate_result"],
font=('Segoe UI', 12, 'bold'),
foreground=self.colors['text'],
style='Modern.TLabel')
self.result_title_label.pack(anchor=tk.W, pady=(0, 15))
# 结果显示 - 简化样式
result_display = ttk.Frame(main_frame,
style='Modern.TFrame',
padding="30")
result_display.pack(fill=tk.BOTH, expand=True, pady=(0, 25))
# 添加结果标签
self.result_label = ttk.Label(result_display,
textvariable=self.result,
font=('Segoe UI', 14, 'bold'),
foreground=self.colors['text'],
wraplength=500,
justify=tk.CENTER,
style='Modern.TLabel')
self.result_label.pack(fill=tk.BOTH, expand=True)
# 按钮区域 - 现代化布局
button_frame = ttk.Frame(main_frame, style='Modern.TFrame')
button_frame.pack(fill=tk.X)
# 重新生成按钮 - 主按钮
self.regenerate_btn = ttk.Button(button_frame,
text=self.translations[self.language]["regenerate"],
command=self.generate,
style='Modern.TButton')
self.regenerate_btn.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 10))
# 复制到剪贴板按钮 - 次要按钮
self.copy_btn = ttk.Button(button_frame,
text=self.translations[self.language]["copy"],
command=self.copy_to_clipboard,
style='Secondary.TButton')
self.copy_btn.pack(side=tk.LEFT, fill=tk.X, expand=True)
# 初始更新UI
self.on_id_type_change(None)
def on_id_type_change(self, event):
# 显示/隐藏高级选项
selected_name = self.current_id_type.get()
selected_keys = [k for k, v in self.id_type_names.items() if v == selected_name]
selected_key = selected_keys[0] if selected_keys else "uuidv4"
# 更新存储的ID类型键
self.current_id_type_key.set(selected_key)
if selected_key in ["uuidv3", "uuidv5"]:
self.namespace_frame.pack(fill=tk.X)
self.prefix_frame.pack_forget()
self.advanced_frame.pack(fill=tk.X, pady=(0, 25))
elif selected_key == "upid":
self.namespace_frame.pack_forget()
self.prefix_frame.pack(fill=tk.X)
self.advanced_frame.pack(fill=tk.X, pady=(0, 25))
else:
self.namespace_frame.pack_forget()
self.prefix_frame.pack_forget()
self.advanced_frame.pack_forget()
self.generate()
def set_random_namespace(self):
self.namespace.set(str(uuid.uuid4()))
self.generate()
def show_predefined_uuids(self):
# 创建预设UUID窗口
predefined_window = tk.Toplevel(self.root)
predefined_window.title(self.translations[self.language]["preset_uuid_title"])
predefined_window.geometry("500x400")
predefined_window.resizable(False, False)
predefined_window.configure(background=self.colors['bg'])
predefined_window.grab_set()
# 主框架
main_frame = ttk.Frame(predefined_window, style='Modern.TFrame', padding="30")
main_frame.pack(fill=tk.BOTH, expand=True)
# 标题
title = ttk.Label(main_frame, text=self.translations[self.language]["select_preset_uuid"],
font=('Segoe UI', 18, 'bold'),
foreground=self.colors['primary'],
style='Modern.TLabel')
title.pack(anchor=tk.CENTER, pady=(0, 25))
# 创建自定义样式的列表框
self.uuid_listbox = tk.Listbox(main_frame,
width=60,
height=8,
font=('Segoe UI', 11),
bg=self.colors['surface'],
fg=self.colors['text'],
borderwidth=1,
relief='solid',
highlightthickness=0,
selectbackground=self.colors['primary'],
selectforeground='white')
self.uuid_listbox.pack(fill=tk.BOTH, expand=True, pady=(0, 25))
# 添加预设UUID到列表
for name, uuid_val in self.predefined_uuids.items():
self.uuid_listbox.insert(tk.END, f"{name}: {uuid_val}")
# 选择按钮
select_btn = ttk.Button(main_frame,
text=self.translations[self.language]["select_preset_uuid"].split(" ")[1],
command=self.on_select_predefined_uuid,
style='Modern.TButton')
select_btn.pack(fill=tk.X)
def toggle_language(self):
"""切换中英文语言"""
# 切换语言
self.language = "en" if self.language == "zh" else "zh"
# 更新翻译后的ID类型名称
self.id_type_names = self.id_type_names_i18n[self.language]
# 更新应用标题
self.root.title(self.translations[self.language]["app_title"])
# 更新所有UI元素的文本
self.title_label.config(text=self.translations[self.language]["app_title"])
self.lang_btn.config(text="EN" if self.language == "zh" else "中文")
self.select_id_type_label.config(text=self.translations[self.language]["select_id_type"])
self.namespace_label.config(text=self.translations[self.language]["namespace"])
self.name_label.config(text=self.translations[self.language]["name"])
self.prefix_label.config(text=self.translations[self.language]["prefix"])
self.result_title_label.config(text=self.translations[self.language]["generate_result"])
self.random_uuid_btn.config(text=self.translations[self.language]["random_uuid"])
self.preset_uuid_btn.config(text=self.translations[self.language]["preset_uuid"])
self.regenerate_btn.config(text=self.translations[self.language]["regenerate"])
self.copy_btn.config(text=self.translations[self.language]["copy"])
# 更新Combobox选项
self.id_type_combo.config(values=list(self.id_type_names.values()))
# 使用存储的ID类型键保持选择一致性
current_key = self.current_id_type_key.get()
self.current_id_type.set(self.id_type_names[current_key])
# 重新生成ID
self.generate()
def on_select_predefined_uuid(self):
selection = self.uuid_listbox.curselection()
if selection:
index = selection[0]
uuid_str = self.uuid_listbox.get(index)
uid = uuid_str.split(": ")[1]
self.namespace.set(uid)
self.generate()
self.uuid_listbox.master.master.destroy() # 关闭窗口
def generate(self):
# 直接使用存储的ID类型键,避免语言切换问题
selected_key = self.current_id_type_key.get()
result = ""
if selected_key == "uuidv1":
result = generate_uuid_v1()
elif selected_key == "uuidv3":
result = generate_uuid_v3(self.namespace.get() or str(uuid.uuid4()), self.name.get() or "test")
elif selected_key == "uuidv4":
result = generate_uuid_v4()
elif selected_key == "uuidv5":
result = generate_uuid_v5(self.namespace.get() or str(uuid.uuid4()), self.name.get() or "test")
elif selected_key == "uuidv6":
result = generate_uuid_v6()
elif selected_key == "uuidv7":
result = generate_uuid_v7()
elif selected_key == "shortuuid":
result = generate_short_uuid()
elif selected_key == "niluuid":
result = generate_nil_uuid()
elif selected_key == "maxuuid":
result = generate_max_uuid()
elif selected_key == "nanoid":
result = generate_nano_id()
elif selected_key == "ulid":
result = generate_ulid()
elif selected_key == "cuid":
result = generate_cuid()
elif selected_key == "cuid2":
result = generate_cuid2()
elif selected_key == "nuid":
result = generate_nuid()
elif selected_key == "snowflake":
result = generate_snowflake()
elif selected_key == "sonyflake":
result = generate_sonyflake()
elif selected_key == "upid":
result = generate_upid(self.prefix.get())
elif selected_key == "tsid":
result = generate_tsid()
elif selected_key == "objectid":
result = generate_object_id()
elif selected_key == "scru128":
result = generate_scru128()
elif selected_key == "hardwareuuid":
result = generate_hardware_uuid()
self.result.set(result)
def copy_to_clipboard(self):
text = self.result.get()
if text:
self.root.clipboard_clear()
self.root.clipboard_append(text)
messagebox.showinfo(self.translations[self.language]["success_copy"],
self.translations[self.language]["success_copy_msg"])
else:
messagebox.showerror(self.translations[self.language]["error_copy"],
self.translations[self.language]["error_copy_msg"])
if __name__ == "__main__":
root = tk.Tk()
app = IDGeneratorApp(root)
root.mainloop()